package com.xmtlxx.web.controller.oms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysDept;
import com.xmtlxx.common.core.domain.entity.SysDictData;
import com.xmtlxx.common.core.domain.model.LoginUser;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.enums.PropertyLogNode;
import com.xmtlxx.common.enums.PropertyLogType;
import com.xmtlxx.common.exception.ServiceException;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.sms.aliyun.AliyunSmsService;
import com.xmtlxx.common.sms.aliyun.SmsRequest;
import com.xmtlxx.common.sms.aliyun.SmsTemplateCode;
import com.xmtlxx.common.sms.aliyun.SmsTemplateParam;
import com.xmtlxx.common.tengbo.PushDatasUtil;
import com.xmtlxx.common.tengbo.vo.*;
import com.xmtlxx.common.utils.DateUtils;
import com.xmtlxx.common.utils.JsonUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.oms.domain.*;
import com.xmtlxx.oms.domain.bo.*;
import com.xmtlxx.oms.domain.vo.*;
import com.xmtlxx.oms.mapper.*;
import com.xmtlxx.system.domain.SysOss;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.enums.OssBuss;
import com.xmtlxx.system.mapper.SysDeptMapper;
import com.xmtlxx.system.mapper.SysDictDataMapper;
import com.xmtlxx.system.mapper.SysOssMapper;
import com.xmtlxx.system.mapper.SysUserMapper;
import com.xmtlxx.system.service.ISysConfigService;
import com.xmtlxx.tms.domain.*;
import com.xmtlxx.tms.domain.bo.OrderBo;
import com.xmtlxx.tms.domain.bo.OrderDtlBo;
import com.xmtlxx.tms.domain.bo.WaybillDtlBo;
import com.xmtlxx.tms.domain.bo.WaybillLogBo;
import com.xmtlxx.tms.domain.vo.OrderVo;
import com.xmtlxx.tms.domain.vo.WaybillVo;
import com.xmtlxx.tms.mapper.*;
import com.xmtlxx.web.controller.center.service.ICommonService;
import com.xmtlxx.web.controller.oms.service.ITaskService;
import com.xmtlxx.wms.domain.*;
import com.xmtlxx.wms.domain.bo.*;
import com.xmtlxx.wms.domain.vo.PickVo;
import com.xmtlxx.wms.domain.vo.*;
import com.xmtlxx.wms.mapper.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 出入库订单Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-12
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TaskServiceImpl implements ITaskService {

    private final TaskMapper baseMapper;

    private final TaskDtlMapper taskDtlMapper;

    private final SysOssMapper sysOssMapper;

    private final OperatorLogMapper logMapper;

    private final PropertyMapper propertyMapper;

    private final PropertyLogMapper propertyLogMapper;

    private final BoxMapper boxMapper;

    private final InventoryMapper inventoryMapper;

    private final StoreMapper storeMapper;

    private final SysDeptMapper deptMapper;

    private final BoxDeptMapper boxDeptMapper;

    private final ClassifyMapper classifyMapper;

    private final WarehouseMapper warehouseMapper;

    private final WarehouseDtlMapper warehouseDtlMapper;

    private final ExWarehouseMapper exWarehouseMapper;

    private final ExWarehouseDtlMapper exWarehouseDtlMapper;

    private final OrderMapper orderMapper;

    private final OrderDtlMapper orderDtlMapper;

    private final OrderLogMapper orderLogMapper;

    private final WaybillMapper waybillMapper;

    private final WaybillDtlMapper waybillDtlMapper;

    private final WaybillLogMapper waybillLogMapper;

    private final DealDtlMapper dealDtlMapper;

    private final ContactsMapper contactsMapper;

    private final ICommonService commonService;

    private final OperatorLogMapper operatorLogMapper;

    private final HandoverMapper handoverMapper;

    private final HandoverDtlMapper handoverDtlMapper;

    private final DealMapper dealMapper;

    private final SysUserMapper userMapper;

    private final ISysConfigService configService;

    private final PickMapper pickMapper;

    private final SysDictDataMapper dictDataMapper;

    private final PickDtlMapper pickDtlMapper;

    private final PutTaskMapper putTaskMapper;

    private final PutDtlMapper putDtlMapper;

    private final TaskDisposalInfoMapper taskDisposalInfoMapper;

    private final AliyunSmsService aliyunSmsService;

    /**
     * 查询出入库订单
     *
     * @param id 出入库订单主键
     * @return 出入库订单
     */
    @Override
    public TaskVo queryById(String id) {
        //return baseMapper.selectVoById(id);
        return baseMapper.selectTaskVoByID(id);
    }

    @Override
    public TaskVo initBean(TaskVo taskVo) {

        TaskVo vo = new TaskVo();
        List<TaskDtlVo> items = new ArrayList<>();
        if (StringUtils.isNotEmpty(taskVo.getId())) {
            vo = baseMapper.selectVoById(taskVo.getId());
            TaskDtlBo dtlBo = new TaskDtlBo();
            dtlBo.setTaskId(vo.getId());
            items = taskDtlMapper.selectTaskDtlList(dtlBo);
        } else {
            vo.setDelivery("0");//物流配送默认为0
            vo.setDeptId(LoginHelper.getDeptId());
            vo.setDeptName(LoginHelper.getLoginUser().getDeptName());

            ContactsVo contactsVo = null;
            ContactsBo contactsBo = new ContactsBo();
            contactsBo.setDeptId(LoginHelper.getDeptId());
            List<ContactsVo> contactsVos = contactsMapper.selectContactsList(contactsBo);
            //获取联系人信息
            if (contactsVos != null && contactsVos.size() > 0) {
                for (ContactsVo contacts : contactsVos) {
                    if (!StringUtils.isEmpty(contacts.getFlag()) && contacts.getFlag().equals("Y")) {
                        contactsVo = contacts;
                        break;
                    }
                }
                if (ObjectUtil.isNull(contactsVo)) {
                    contactsVo = contactsVos.get(0);
                }
            }
            if (ObjectUtil.isNotNull(contactsVo)) {
                vo.setName(contactsVo.getName());
                vo.setTel(contactsVo.getTel());
                vo.setAddress(contactsVo.getAddress());
            }


            switch (taskVo.getType()) {
                case "1":
                    vo.setTakeDept(vo.getDeptId());
                    vo.setTakeContacts(vo.getName());
                    vo.setTakeTel(vo.getTel());
                    vo.setTakeAddress(vo.getAddress());
                    break;
                case "2":
                    vo.setIsTrailer("1");
                    vo.setBackOss(new ArrayList<>());
                    //处置申请 ：发还环节
//                    if(StringUtils.isNotEmpty(taskVo.getSubmitType()) && taskVo.getSubmitType().equals("back")){
//                        vo.setDelivery("1");//自行配送
//                        vo.setName(LoginHelper.getNickname());
//                        vo.setTel(userMapper.selectUserById(LoginHelper.getUserId()).getPhonenumber());
//                        vo.setBackOss(new ArrayList<>());
//                        vo.setDealType("3");
//                        vo.setSubmitType("back");//
//                    }

                    break;
                case "3":
                    break;
            }
        }

        List<StoreVo> storeVoList = storeMapper.selectStoreList(new StoreBo());
        List<SysDictData> dictDataList = dictDataMapper.selectDictDataByType("oms_property_type");
        List<StoreDictVo> dictList = dictDataList.stream().map(dict -> {
            StoreDictVo dictVo = new StoreDictVo();
            dictVo.setLabel(dict.getDictLabel());
            dictVo.setValue(dict.getDictValue());
            switch (dict.getDictValue()) {
                case "3":
                    dictVo.setStoreId(storeVoList.get(1).getId());
                    dictVo.setName(storeVoList.get(1).getName());
                    break;
                default:
                    dictVo.setStoreId(storeVoList.get(0).getId());
                    dictVo.setName(storeVoList.get(0).getName());
                    break;
            }
            return dictVo;
        }).collect(Collectors.toList());
        vo.setDictList(dictList);
        vo.setItems(items);
        vo.setType(taskVo.getType());
        return vo;
    }

    @Override
    public TaskVo initReturnBean(TaskVo taskVo) {

        TaskVo vo = new TaskVo();

        vo.setId(taskVo.getId());
        vo.setDelivery("0");//物流配送默认为0
        vo.setType("3");
        vo.setDeptId(LoginHelper.getDeptId());
        vo.setDeptName(LoginHelper.getLoginUser().getDeptName());
        vo.setRevertMold("0");
        vo.setAddType("return");

        ContactsVo contactsVo = null;
        ContactsBo contactsBo = new ContactsBo();
        contactsBo.setDeptId(LoginHelper.getDeptId());
        List<ContactsVo> contactsVos = contactsMapper.selectContactsList(contactsBo);
        //获取联系人信息
        if (contactsVos != null && contactsVos.size() > 0) {
            for (ContactsVo contacts : contactsVos) {
                if (!StringUtils.isEmpty(contacts.getFlag()) && contacts.getFlag().equals("Y")) {
                    contactsVo = contacts;
                    break;
                }
            }
            if (ObjectUtil.isNull(contactsVo)) {
                contactsVo = contactsVos.get(0);
            }
        }
        if (ObjectUtil.isNotNull(contactsVo)) {
            vo.setName(contactsVo.getName());
            vo.setTel(contactsVo.getTel());
            vo.setAddress(contactsVo.getAddress());
        }


        TaskVo entyVo = baseMapper.selectTaskVoByID(taskVo.getId());

        //绑定归还入库单
        vo.setReturnId(entyVo.getId());

        TaskDtlBo dtlBo = new TaskDtlBo();
        dtlBo.setTaskId(entyVo.getId());
        TaskBo taskBo = new TaskBo();
        taskBo.setReturnId(vo.getId());
        List<TaskDtlVo> items = taskDtlMapper.selectTaskDtlList(dtlBo);
        List<TaskDtlVo> result = new ArrayList<>();
        List<TaskVo> taskList = baseMapper.selectTaskList(taskBo);
        if (taskList != null && taskList.size() > 0) {
            for (TaskVo item : taskList) {
                TaskDtlBo dBo = new TaskDtlBo();
                dBo.setTaskId(item.getId());
                List<TaskDtlVo> dItems = taskDtlMapper.selectTaskDtlList(dBo);

                result = items.stream().map(oldVals -> {
                    dItems.stream().filter(reduceVals -> Objects.equals(oldVals.getPno(), reduceVals.getPno())).forEach(reduceVals -> {
                        Long nums = oldVals.getNums() - reduceVals.getNums();
                        oldVals.setNums(nums);//重新计算归还数量
                    });
                    if (oldVals.getNums() != 0L) {
                        return oldVals;
                    }
                    return null;
                }).filter(Objects::nonNull).collect(Collectors.toList());
            }
        } else {
            result = items;
        }

        vo.setItems(result);
        vo.setOss(new ArrayList<>());
        return vo;
    }

    /**
     * 初始化转处置页面
     *
     * @param taskVo
     * @return
     */
    @Override
    public TaskVo initReplaceBean(TaskVo taskVo) {

        TaskVo vo = baseMapper.selectTaskVoByID(taskVo.getId());

        TaskDtlBo dtlBo = new TaskDtlBo();
        dtlBo.setTaskId(vo.getId());
        List<TaskDtlVo> items = taskDtlMapper.selectTaskDtlList(dtlBo);
        List<TaskDtlVo> result = new ArrayList<>();
        TaskBo taskBo = new TaskBo();
        taskBo.setReturnId(vo.getId());
        List<TaskVo> taskList = baseMapper.selectTaskList(taskBo);
        if (taskList != null && taskList.size() > 0) {
            for (TaskVo item : taskList) {
                TaskDtlBo dBo = new TaskDtlBo();
                dBo.setTaskId(item.getId());
                List<TaskDtlVo> dItems = taskDtlMapper.selectTaskDtlList(dBo);

                result = items.stream().map(oldVals -> {
                    dItems.stream().filter(reduceVals -> Objects.equals(oldVals.getPno(), reduceVals.getPno())).forEach(reduceVals -> {
                        Long nums = oldVals.getNums() - reduceVals.getNums();
                        oldVals.setNums(nums);//重新计算归还数量
                    });
                    if (oldVals.getNums() != 0L) {
                        return oldVals;
                    }
                    return null;
                }).collect(Collectors.toList());

            }
        } else {
            result = items;
        }

        vo.setItems(result);

        vo.setIsCheck("0");
        vo.setReplaceNo(vo.getTaskNo());
        vo.setOss(new ArrayList<>());
        return vo;
    }

    /**
     * 查询出入库订单列表
     *
     * @param bo 出入库订单
     * @return 出入库订单
     */
    @Override
    public TableDataInfo<TaskVo> queryPageList(TaskBo bo, PageQuery pageQuery) {

        Page<TaskVo> result = baseMapper.selectPageTaskList(pageQuery.build(), bo);
        if (result != null && result.getRecords() != null && result.getRecords().size() > 0) {
            for (TaskVo vo : result.getRecords()) {
                if (vo.getType().equals("3") || vo.getType().equals("2") || vo.getType().equals("1")) {
                    OrderBo orderBo = new OrderBo();
                    orderBo.setTaskId(vo.getId());
                    List<OrderVo> orderVos = orderMapper.selectOrderList(orderBo);
                    if (orderVos != null && orderVos.size() > 0) {
                        OrderVo order = orderVos.get(0);
                        WaybillVo waybillVo = waybillMapper.selectWaybillVoByOrderID(order.getId());
                        if (waybillVo != null) {
                            vo.setWaybillId(waybillVo.getId());
                            if (waybillVo.getStatus().equals("5")) {
                                vo.setIsWaybillShow(true);
                            }
                        }
                    }
                    ExWarehouseVo exWarehouseVo = exWarehouseMapper.selectExWarehouseVoByTaskId(vo.getId());
                    if (exWarehouseVo != null) {
                        vo.setIsSign(exWarehouseVo.getIsSign());
                        vo.setExWarehouseId(exWarehouseVo.getId());
                    }
                    vo.setIsCheck("1");
                    if (LoginHelper.getLoginUser().getRolePermission().contains("centercangguang")) {
                        vo.setIsShowBtn(true);
                    }
                }

                //获取物品名称
                String propertyNames = "";
                TaskDtlBo dtlBo = new TaskDtlBo();
                dtlBo.setTaskId(vo.getId());
                dtlBo.setDelFlag("0");
                List<TaskDtlVo> dtlVos = taskDtlMapper.selectTaskDtlList(dtlBo);
                if (dtlVos != null && dtlVos.size() > 0) {
                    propertyNames = dtlVos.stream().map(TaskDtlVo::getName).collect(Collectors.joining("|"));
                }
                vo.setPropertyNames(propertyNames);
            }
        }
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<TaskVo> queryPageListWithOutLogin(TaskBo bo, PageQuery pageQuery) {

        Page<TaskVo> result = baseMapper.selectPageTaskListWithOutLogin(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    @Override
    public TaskVo initDealBean(List<String> ids) {

        TaskVo vo = new TaskVo();
        //申请时间
        vo.setRequestTime(new Date());
        //物流配送默认为0
        vo.setDelivery("0");
        vo.setType("2");
        //状态
        vo.setStatus("0");
        vo.setOss(new ArrayList<>());
        vo.setDeptId(LoginHelper.getDeptId());
        vo.setDeptName(LoginHelper.getLoginUser().getDeptName());

        ContactsVo contactsVo = null;
        ContactsBo contactsBo = new ContactsBo();
        contactsBo.setDeptId(LoginHelper.getDeptId());
        List<ContactsVo> contactsVos = contactsMapper.selectContactsList(contactsBo);
        //获取联系人信息
        if (contactsVos != null && contactsVos.size() > 0) {
            for (ContactsVo contacts : contactsVos) {
                if (!StringUtils.isEmpty(contacts.getFlag()) && contacts.getFlag().equals("Y")) {
                    contactsVo = contacts;
                    break;
                }
            }
            if (ObjectUtil.isNull(contactsVo)) {
                contactsVo = contactsVos.get(0);
            }
        }
        if (ObjectUtil.isNotNull(contactsVo)) {
            vo.setName(contactsVo.getName());
            vo.setTel(contactsVo.getTel());
            vo.setAddress(contactsVo.getAddress());
        }


        if (ids != null && ids.size() > 0) {
            List<TaskDtlVo> taskDtls = ids.stream().map(item -> {
                TaskDtlVo dtl = new TaskDtlVo();
                DealDtlVo dtlVo = dealDtlMapper.selectVoOne(new LambdaQueryWrapper<DealDtl>().eq(DealDtl::getDealId, item));
                BeanUtil.copyProperties(dtlVo, dtl, "id");
                return dtl;
            }).collect(Collectors.toList());
            vo.setItems(taskDtls);
        }

        return vo;
    }

    /**
     * 查询出入库订单列表
     *
     * @param bo 出入库订单
     * @return 出入库订单
     */
    @Override
    public List<TaskVo> queryList(TaskBo bo) {
        // LambdaQueryWrapper<Task> lqw = buildQueryWrapper(bo);
        // return baseMapper.selectVoList(lqw);
        return baseMapper.selectTaskList(bo);
    }

    @Override
    public List<TaskVo> taskStatistics() {

        return baseMapper.taskStatistics();
    }

    @Override
    public List<TaskVo> outTaskStatistics(TaskBo task) {

        return baseMapper.outTaskStatistics(task);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskVo getTaskById(String id) {

        TaskVo vo = baseMapper.selectTaskVoByID(id);
        TaskDtlBo bo = new TaskDtlBo();
        bo.setTaskId(id);
        bo.setDelFlag(vo.getDelFlag());
        List<TaskDtlVo> items = taskDtlMapper.selectTaskDtlList(bo);
        if (items != null && items.size() > 0) {
            items.forEach(item -> {
                SysOssBo ossBo = new SysOssBo();
                ossBo.setObjid(item.getPno());
                ossBo.setBuss("property");
                item.setOss(sysOssMapper.selectPropertySysOssList(ossBo));
            });
        }
        vo.setItems(items);
        vo.setCarKey(items.get(0).getCarKey());
        vo.setDriveLicen(items.get(0).getDriveLicen());
        vo.setRegisterBook(items.get(0).getRegisterBook());
        if (vo.getStatus().equals("1")) {
            vo.setIsUpdate(true);
        } else {
            switch (vo.getType()) {
                case "0":

                    //入库申请，已取件后，不可编辑
                    HandoverBo handoverBo = new HandoverBo();
                    handoverBo.setType("0");
                    handoverBo.setStatus("1");
                    handoverBo.setObjid(id);
                    HandoverVo handoverVo = handoverMapper.selectHandoverVoByObjid(handoverBo);
                    if (handoverVo != null) {
                        vo.setIsUpdate(true);
                    }


                    break;
                case "2":
                    //处理pdf附件
                    if (items != null && items.size() > 0) {
                        items.stream().forEach(dtl -> {
                            DealDtlBo dealDtlBo = new DealDtlBo();
                            dealDtlBo.setTaskId(vo.getId());
                            dealDtlBo.setPno(dtl.getPno());
                            List<DealDtlVo> dealDtlVos = dealDtlMapper.selectDealDtlList(dealDtlBo);
                            if (dealDtlVos != null && dealDtlVos.size() > 0) {
                                List<String> pdfList = new ArrayList<>();
                                dealDtlVos.stream().forEach(dealDtlVo -> {

                                    if (StringUtils.isNotEmpty(dealDtlVo.getWsPdf())) {
                                        String json = dealDtlVo.getWsPdf();
                                        if (!json.startsWith("[")) {
                                            if (!json.startsWith("'") && !json.endsWith("'")) {
                                                json = "'" + json + "'";
                                            }
                                            json = "[" + json + "]";
                                        }
                                        JSONArray wsPdfDatas = JSONArray.parseArray(json);
                                        wsPdfDatas.removeAll(Collections.singleton(null));
                                        for (int i = 0; i < wsPdfDatas.size(); i++) {
                                            pdfList.add(wsPdfDatas.get(i).toString());
                                        }
                                    }
                                });
                                dtl.setPdfList(pdfList);
                            }
                        });
                    }

                    break;
                default:
                    //出库，调用，处置，已审核后，不可编辑
                    if (StringUtils.isNotBlank(vo.getCheckStatus()) && vo.getCheckStatus().equals("1")) {
                        vo.setIsUpdate(true);
                    }
                    break;
            }

        }


        //订单类型
        String taskType = null;
        if (StringUtils.isNotEmpty(vo.getType())) {
            switch (vo.getType()) {
                case "0":
                    taskType = "oms_warehouse";
                    if (StringUtils.isNotEmpty(vo.getReturnId())) {
                        taskType = "return_task";
                    }
                    if (StringUtils.isNotEmpty(vo.getReturnId())) {
                        TaskVo rvo = baseMapper.selectTaskVoByID(vo.getReturnId());
                        vo.setTransferNo(rvo.getTaskNo());
                    }
                    break;
                case "1":
                    taskType = "oms_exWarehouse";
                    break;
                case "2":
                    //发还身份证附件
//                    SysOssBo dOss = new SysOssBo();
//                    dOss.setObjid(vo.getId());
//                    dOss.setBuss("backDeal");
//                    vo.setBackOss(sysOssMapper.selectSysOssList(dOss));
//                    if(StringUtils.isNotEmpty(vo.getInfo())){
//                        vo.setSubmitType("back");
//                    }
                    TaskDisposalInfo disposalInfo = taskDisposalInfoMapper.getDisposalInfo(vo.getId());

                    List<SysOss> sysOsses = sysOssMapper.selectSysOssList(new SysOssBo(vo.getId(), OssBuss.DISPOSAL_APPLY_CERT.getValue()));
                    disposalInfo.setCertNoPhotoOss(sysOsses);
                    vo.setDisposalInfo(disposalInfo);
                    taskType = "oms_deal";
                    break;
                case "3":
                    taskType = "oms_transfer";
                    break;
                default:
                    break;
            }
        }
        SysOssBo oss = new SysOssBo();
        if (StringUtils.isNotEmpty(vo.getReturnId())) {
            oss.setObjid(vo.getReturnId());
        } else {
            oss.setObjid(vo.getId());
        }
        oss.setBuss(taskType);
        vo.setOss(sysOssMapper.selectSysOssList(oss));

        SysOssBo bussBo = new SysOssBo();
        bussBo.setObjid(vo.getId());
        bussBo.setBuss("dealsForm");
        vo.setDealsOss(sysOssMapper.selectSysOssList(bussBo));

        bussBo.setBuss("taskVideo");
        vo.setVideoList(sysOssMapper.selectSysOssList(bussBo));

        /**
         * 处理交接原件问题
         */
//        updateHandoverPics(vo.getId());
        return vo;
    }

    private LambdaQueryWrapper<Task> buildQueryWrapper(TaskBo bo) {

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Task> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTaskNo()), Task::getTaskNo, bo.getTaskNo());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), Task::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getStoreId()), Task::getStoreId, bo.getStoreId());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckStatus()), Task::getCheckStatus, bo.getCheckStatus());
        lqw.eq(bo.getDeptId() != null, Task::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Task::getStatus, bo.getStatus());
        lqw.eq(bo.getUpdateTime() != null, Task::getUpdateTime, bo.getUpdateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getTel()), Task::getTel, bo.getTel());
        lqw.like(StringUtils.isNotBlank(bo.getName()), Task::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Task::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    @Override
    public TaskVo selectTaskVoByTaskNo(TaskBo task) {

        return baseMapper.selectTaskVoByTaskNo(task);
    }

    /**
     * 新增出入库订单
     *
     * @param bo 出入库订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskVo insertByBo(TaskBo bo) {

        Task add = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(add);

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        add.setSource(StringUtils.isNotEmpty(bo.getSource()) ? bo.getSource() : "0");
        String num = "";
        String content = "";
        String buss = "";
        String logType = "";
        if (StringUtils.isNotEmpty(add.getType())) {
            switch (add.getType()) {
                case "0":
                    num = "R";
                    content = "创建入库申请";
                    buss = "warehouseDtl";
                    logType = "1";
                    break;
                case "1":
                    num = "E";
                    content = "创建出库申请";
                    buss = "exWarehouseDtl";
                    logType = "2";
                    break;
                case "2":
                    num = "C";
                    content = "创建处置申请";
                    buss = "dealDtl";
                    logType = "4";
                    break;
                case "3":
                    num = "D";
                    content = "创建调用申请";
                    buss = "transferDtl";
                    logType = "3";
                    break;
                default:
                    break;
            }
        }
        add.setTaskNo(getNo(num));

        List<TaskDtl> dtls = new ArrayList<>();
        Long nums = 0L;
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            for (TaskDtlVo item : bo.getItems()) {
                TaskDtl dtl = BeanUtil.toBean(item, TaskDtl.class);
                dtl.setId(IdUtil.simpleUUID());
                dtl.setTaskId(add.getId());
                dtl.setDelFlag("0");
                dtl.setStatus("0");
                dtl.setNums(item.getNums() == null ? 1L : item.getNums());
                if (add.getType().equals("2")) {
                    if (StringUtils.isEmpty(item.getDealType())) {
                        dtl.setDealType(add.getDealType());
                    }
                }
                if (item.getOss() != null && item.getOss().size() > 0) {
                    for (SysOss oss : item.getOss()) {
                        oss.setBuss(buss);
                        oss.setObjid(dtl.getId());
                        sysOssMapper.updateById(oss);
                    }
                }

                //判断当前入库,待移交财物进行移交操作
                Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, dtl.getPno()));
                if (property != null && StringUtils.isNotEmpty(property.getTransferStatus()) && property.getTransferStatus().equals("0")) {
                    property.setTransferStatus("1");
                    propertyMapper.updateById(property);
                }

                dtls.add(dtl);
                nums += dtl.getNums();

                String logContent = content + "：(物品编号：" + dtl.getPno() + "，物品名称：" + dtl.getName() + "，申请说明：" + (StringUtils.isNotEmpty(add.getRemark()) ? add.getRemark() : "") + ")";
                PropertyLog propertyLog = saveLog(logType, dtl, add.getId(), add.getStoreId(), content, add.getDeptId(), LoginHelper.getLoginUser(), null);
//                propertyLogMapper.insert(propertyLog);
                PropertyLogModelsVo data = new PropertyLogModelsVo();
                data.setApi("proBase");
                data.setData(propertyLogMapper.selectPropertyLogVoByID(propertyLog.getId()));
                PushDatasUtil.pushPropertyDatas(data);
            }
        }
        add.setNums(nums);
        boolean flag = baseMapper.insert(add) > 0;
        if (dtls != null && dtls.size() > 0) {
            taskDtlMapper.insertBatch(dtls);
        }
        if (flag) {
            bo.setId(add.getId());
        }

        addOperatorLog(add.getId(), "oms", content);

        TaskVo vo = new TaskVo();
        BeanUtil.copyProperties(add, vo);

        return vo;
    }

    /**
     * 新增出入库订单
     *
     * @param bo 出入库订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskVo insertByBoV2(TaskBo bo) {

        Task add = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(add);


        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        add.setSendStatus("0");
        add.setSendReStatus("0");
        //设置来源 0-自主创建 1-市级下发
        add.setSource(StringUtils.isNotEmpty(bo.getSource()) ? bo.getSource() : "0");

        String taskNo = "";
        //流转日志内容
        String operatorContent = "";
        //财物日志类型
        String logType = "";
        //订单类型
        String taskType = "";

        if (StringUtils.isNotEmpty(add.getType())) {
            switch (add.getType()) {
                case "0":
                    taskNo = "R";
                    operatorContent = "创建入库申请";
                    logType = PropertyLogType.WAREHOUSE_TASK.getCode();
                    taskType = "oms_warehouse";
                    break;
                case "1":
                    taskNo = "E";
                    operatorContent = "创建出库申请";
                    logType = PropertyLogType.EX_WAREHOUSE_TASK.getCode();
                    taskType = "oms_exWarehouse";
                    break;
                case "3":
                    taskNo = "D";
                    operatorContent = "创建调用申请";
                    logType = PropertyLogType.TRANSFER_TASK.getCode();
                    taskType = "oms_transfer";
                    break;
                default:
                    break;
            }
        }
        add.setTaskNo(getNo(taskNo));//设置编号

        //设置是否车辆单
        if (StringUtils.isNotEmpty(bo.getPropertyType()) && bo.getPropertyType().equals("3")) {
            add.setBuss("1");
        } else {
            add.setBuss("0");
        }

        //设置财物清单
        Long nums = 0L;
        List<TaskDtl> dtls = new ArrayList<>();
        List<PropertyLog> logs = new ArrayList<>();
        List<Inventory> inventories = new ArrayList<>();


        if (bo.getItems() != null && bo.getItems().size() > 0) {
            List<Box> boxes = new ArrayList<>();
            dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl, "id");
                dtl.setId(IdUtil.simpleUUID());
                dtl.setTaskId(add.getId());
                dtl.setDelFlag("0");
                dtl.setStatus("0");
                if (StringUtils.isNotEmpty(bo.getPassword())) {
                    dtl.setPassword(bo.getPassword());//设置保管密码
                }


                //箱号设置
                //判断是否是扫码箱子，或者是手动输入
                Box box = null;
                if (StringUtils.isNotEmpty(dtl.getBoxId())) {
                    box = boxMapper.selectById(dtl.getBoxId());
                    //箱子所在部门与申请账号部门不一致时，变更箱子所在部门为当前账号部门
                    if (box.getDeptId() != null && (!box.getDeptId().equals(LoginHelper.getDeptId()))) {
                        box.setDeptId(LoginHelper.getDeptId());
                    }
                    if (box.getStatus().equals("0")) {
                        //设置为已使用
                        box.setStatus("1");
                    }
                    boxMapper.insertOrUpdate(box);
                } else {
                    //手动输入箱号
                    if (StringUtils.isNotEmpty(dtl.getBoxNo())) {
                        box = boxMapper.selectOne(new LambdaQueryWrapper<Box>().eq(Box::getBoxNo, dtl.getBoxNo()));
                        if (box == null) {
                            box = new Box();
                            box.setId(IdUtil.simpleUUID());
                            box.setBoxNo(dtl.getBoxNo());
                            box.setDeptId(LoginHelper.getDeptId());
                            box.setCreateDept(LoginHelper.getDeptId());
                            box.setDelFlag("0");
                            box.setStatus("1");
                            boxMapper.insert(box);
                        }
                        //箱子所在部门与申请账号部门不一致时，变更箱子所在部门为当前账号部门
                        if (box.getDeptId() != null && (!box.getDeptId().equals(LoginHelper.getDeptId()))) {
                            box.setDeptId(LoginHelper.getDeptId());
                        }
                        if (box.getStatus().equals("0")) {
                            //设置为已使用
                            box.setStatus("1");
                        }
                        boxMapper.insertOrUpdate(box);
                    }
                }

                if (box != null) {
                    dtl.setBoxId(box.getId());
                    if (!boxes.contains(box)) {
                        boxes.add(box);
                    }
                }


                //财物处置方式
                if (add.getType().equals("2")) {
                    dtl.setDealType(StringUtils.isNotEmpty(dtl.getDealType()) ? dtl.getDealType() : add.getDealType());

                    //附件
                    if (item.getOss() != null && item.getOss().size() > 0) {
                        for (SysOss oss : bo.getOss()) {
                            oss.setBuss("dealDtl");
                            oss.setObjid(item.getId());
                            sysOssMapper.updateById(oss);
                        }
                    }
                }

                //判断当前入库,待移交财物进行移交操作
                if (add.getType().equals("0")) {
                    Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, dtl.getPno()));
                    if (property != null) {
                        //更新所队移交状态
                        property.setTransferStatus("2");
                        if (StringUtils.isNotEmpty(add.getStoreId())) {
                            property.setBelongDeptId(storeMapper.selectStoreVoByID(add.getStoreId()).getDeptId());
                        } else {
                            property.setBelongDeptId(deptMapper.selectVoById(LoginHelper.getDeptId()).getParentId());
                        }
                        //更新区县移交状态
//                    property.setCountyTransferStatus(finalCountyTransferStatus);
                        propertyMapper.updateById(property);
                    }
                }
                //调用申请
                if (add.getType().equals("3")) {
                    Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, dtl.getPno()));
                    if (property != null) {
                        property.setNums(property.getNums() - dtl.getNums());//库存减去调用数
                        property.setTnums(dtl.getNums());//设置调用数
                        propertyMapper.updateById(property);
                    }

                    Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>().eq(Inventory::getPno, dtl.getPno()));
                    if (inventory != null) {
                        inventory.setNums(inventory.getNums() - dtl.getNums());//库存减去调用数
                        inventory.setTnums(dtl.getNums());//设置调用数
                        inventoryMapper.updateById(inventory);
                    }
                }
                //处置申请
                if (add.getType().equals("2")) {
                    Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, dtl.getPno()));
                    if (property != null) {
                        property.setNums(property.getNums() - dtl.getNums());//库存减去处置数
                        property.setDeals(dtl.getNums());//设置处置数
                        propertyMapper.updateById(property);
                    }

                    Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>().eq(Inventory::getPno, dtl.getPno()));
                    if (inventory != null) {
                        inventory.setNums(inventory.getNums() - dtl.getNums());//库存减去处置数
                        inventory.setDeals(dtl.getNums());//设置处置数
                        inventoryMapper.updateById(inventory);
                    }
                }

                return dtl;
            }).collect(Collectors.toList());

            //箱子使用记录
            if (boxes != null && boxes.size() > 0) {
                for (Box box : boxes) {
                    BoxDept boxDept = new BoxDept();
                    boxDept.setId(IdUtil.simpleUUID());
                    boxDept.setBoxId(box.getId());
                    boxDept.setBoxNo(box.getBoxNo());
                    boxDept.setBoxDept(box.getDeptId());
                    boxDept.setStatus("1");
                    boxDept.setDelFlag("0");
                    boxDeptMapper.insert(boxDept);
                }
            }


            //计算财物数量
            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();

            //库存变动记录
//            inventories = bo.getItems().stream().map(item->{
//                Long befores = 0l;
//                Long count = 0l;
//                Long afters = 0l;
//                Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>()
//                    .eq(Inventory::getPno,item.getPno())
//                    .eq(Inventory::getDeptId,item.getDeptId())
//                    .eq(Inventory::getStatus,"0"));
//                befores = inventory.getNums();
//                count = inventory.getNums();
//                afters = befores - count;
//
//                inventory.setStatus("1");//更新为不在库
//                inventory.setNums(afters);
//                addInventoryLog(inventory,befores,count,afters,add.getId(),add.getType());
//
//                return  inventory;
//            }).collect(Collectors.toList());

            for (TaskDtlVo item : bo.getItems()) {
                Long befores = 0L;
                Long count = 0L;
                Long afters = 0L;
                Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>()
                        .eq(Inventory::getPno, item.getPno())
                        .eq(Inventory::getDeptId, item.getDeptId())
                        .eq(Inventory::getStatus, "0"));
                if (inventory == null) {
                    continue;
                }
                befores = inventory.getNums();
                count = inventory.getNums();
                afters = befores - count;

                inventory.setStatus("1");//更新为不在库
                inventory.setNums(afters);
                addInventoryLog(inventory, befores, count, afters, add.getId(), add.getType());
                inventories.add(inventory);
            }
        }
        add.setNums(nums);

        boolean flag = baseMapper.insert(add) > 0;
        if (dtls != null && dtls.size() > 0) {
            taskDtlMapper.insertBatch(dtls);
        }

        List<SysOss> osses = new ArrayList<>();
        //附件
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            for (SysOss oss : bo.getOss()) {
                oss.setBuss(taskType);
                oss.setObjid(add.getId());
                sysOssMapper.updateById(oss);
                osses.add(oss);
            }
        }

        String finalLogType = logType;
        String finalOperatorContent = operatorContent;
        LoginUser loginUser = LoginHelper.getLoginUser();
        logs = dtls.stream().map(item -> {
            String logContent = finalOperatorContent + "：(物品编号：" + item.getPno() + "，物品名称：" + item.getName() + "，申请说明：" + (StringUtils.isNotEmpty(add.getRemark()) ? add.getRemark() : "") + ")";
            return saveLog(finalLogType, item, add.getId(), add.getStoreId(), finalOperatorContent, add.getDeptId(), loginUser, osses);
        }).collect(Collectors.toList());

        if (logs != null && logs.size() > 0) {
//            propertyLogMapper.insertBatch(logs);
            for (PropertyLog plog : logs) {
                PropertyLogModelsVo data = new PropertyLogModelsVo();
                data.setApi("proBase");
                data.setData(propertyLogMapper.selectPropertyLogVoByID(plog.getId()));
                PushDatasUtil.pushPropertyDatas(data);
            }
        }

        //库存变动为不在库
        if (inventories != null && inventories.size() > 0) {
            inventoryMapper.updateBatchById(inventories);
        }

        List<OperatorLog> oplogs = new ArrayList<>();

        if (flag) {
            bo.setId(add.getId());
            //操作日志
            oplogs.add(addOperatorLog(add.getId(), "oms", operatorContent));
        }
        TaskVo vo = new TaskVo();
        BeanUtil.copyProperties(add, vo);


        //数据推送
        if (add.getSource().equals("0") && StringUtils.isNotEmpty(add.getType())) {
            vo = baseMapper.selectTaskVoByID(add.getId());
            OperatorLogBo logBo = new OperatorLogBo();
            logBo.setObjid(add.getId());
            logBo.setLogType("oms");
//            List<OperatorLogVo> inlogs = logMapper.selectOperatorLogList(logBo);
            switch (add.getType()) {
                case "0":
                    InTaskDatasVo data = BeanUtil.toBean(vo, InTaskDatasVo.class);
                    List<InTaskDatasDtlVo> items = dtls.stream().map(item -> {
                        InTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, InTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    data.setItems(items);
                    data.setLogs(oplogs);
                    PushDatasUtil.pushInTaskDatas(data);
                    break;
                case "1":
                    OutTaskDatasVo outData = BeanUtil.toBean(vo, OutTaskDatasVo.class);
                    List<OutTaskDatasDtlVo> outItems = dtls.stream().map(item -> {
                        OutTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, OutTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    outData.setItems(outItems);
                    outData.setLogs(oplogs);
                    PushDatasUtil.pushOutTaskDatas(outData);
                    break;
                case "3"://"创建调用申请"

                    break;
                default:
                    break;
            }
        }

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskVo insertTaskBo(TaskBo bo) {

        Task add = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(add);

        /**
         * 默认配置
         */
        add.setId(IdUtil.simpleUUID());
        add.setStatus("0");
        add.setDelFlag("0");

        /**
         * 下发状态
         */
        add.setSendStatus("0");
        add.setSendReStatus("0");

        /**
         * buss 类型
         * 0-物品 1-车辆
         */
        StoreVo storeVo = storeMapper.selectVoById(add.getStoreId());
        if (storeVo != null) {
            if (storeVo.getName().equals("车辆仓")) {
                add.setBuss("1");
            } else {
                add.setBuss("0");
            }
        }
        /**
         * 设置审核状态
         * 非入库单
         */
        if (!add.getType().equals("0")) {//自行上门 需审核
            if (add.getType().equals("2")) {//处置申请默认审核通过
                add.setCheckStatus("1");
                if (add.getDelivery().equals("1")
                        ||
                        (!StringUtils.isEmpty(add.getIsTrailer()) && add.getIsTrailer().equals("1"))) {
                    add.setCheckStatus("0");
                }
            } else {
                if (add.getDelivery().equals("0")) {
                    add.setCheckStatus("1");
                } else {
                    add.setCheckStatus("0");
                }
            }
        }
        /**
         * 来源
         */
        add.setSource(StringUtils.isNotEmpty(bo.getSource()) ? bo.getSource() : "0");

        String ossBuss = null;
        String head = null;
        String logType = null;
        String content = null;
        String orderType = null;
        /**
         * type
         * 0-入库 1-出库 2-处置 3-调用
         */
        switch (bo.getType()) {
            case "0":
                head = "R";
                ossBuss = "oms_warehouse";
                logType = PropertyLogType.WAREHOUSE_TASK.getCode();
                content = PropertyLogType.WAREHOUSE_TASK.getInfo();
                orderType = "入库";
                break;
            case "1":
                head = "E";
                ossBuss = "oms_exWarehouse";
                logType = PropertyLogType.EX_WAREHOUSE_TASK.getCode();
                content = PropertyLogType.EX_WAREHOUSE_TASK.getInfo();
                orderType = "出库";
                break;
            case "2":
                head = "C";
                ossBuss = "oms_deal";
                logType = PropertyLogType.DISPOSAL_TASK.getCode();
                content = PropertyLogType.DISPOSAL_TASK.getInfo();
                orderType = "处置";

                if (StringUtils.isEmpty(add.getIsTrailer())) {
                    add.setIsTrailer("0");//中心仓管处理授权 0-未授权 1-已授权
                }

                /**
                 * 处置申请
                 * 发还申请 dealType-3返回当事人
                 * 从发还申请提交的申请单 back
                 */
                if (StringUtils.isNotEmpty(bo.getSubmitType()) && bo.getSubmitType().equals("back") && bo.getDealType().equals("3")) {

                    TaskBo info = new TaskBo();
                    info.setPolice(bo.getPolice());
                    info.setPoliceTel(bo.getPoliceTel());
                    info.setBacker(bo.getBacker());
                    info.setBackTel(bo.getBackTel());
                    info.setBackCard(bo.getBackCard());
                    //身份证附件
                    if (bo.getBackOss() != null && bo.getBackOss().size() > 0) {
                        for (SysOss oss : bo.getBackOss()) {
                            oss.setObjid(add.getId());
                            oss.setBuss("backDeal");
                            sysOssMapper.updateById(oss);
                        }
                    }
                    add.setInfo(JsonUtils.toJsonString(info));
                } else if (bo.getDelivery().equals("1")) {//非发还申请，是自行配送
                    TaskBo info = new TaskBo();
                    info.setPickuper(bo.getPickuper());
                    info.setPickupTel(bo.getPickupTel());
                    info.setPickupCardType(bo.getPickupCardType());
                    info.setPickupCard(bo.getPickupCard());
                    add.setInfo(JsonUtils.toJsonString(info));
                }
                break;
            case "3":
                head = "D";
                ossBuss = "oms_transfer";
                logType = PropertyLogType.TRANSFER_TASK.getCode();
                content = PropertyLogType.TRANSFER_TASK.getInfo();
                orderType = "调用";
                break;
        }

        if (bo.getDelivery().equals("1")) {
            switch (bo.getType()) {
                case "0":
                    break;
                case "2":
                    break;
                default:
                    TaskBo info = new TaskBo();
                    info.setPickuper(bo.getPickuper());
                    info.setPickupTel(bo.getPickupTel());
                    info.setPickupCardType(bo.getPickupCardType());
                    info.setPickupCard(bo.getPickupCard());
                    add.setInfo(JsonUtils.toJsonString(info));
                    break;
            }
        }

        add.setTaskNo(getNo(head));//设置编号
        List<TaskDtl> dtls = new ArrayList<>();
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            String finalContent = content;
            String finalLogType = logType;
            dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl);
                dtl.setId(IdUtil.simpleUUID());
                dtl.setTaskId(add.getId());
                dtl.setDelFlag("0");
                dtl.setStatus("0");

                switch (add.getType()) {
                    case "0":
                        /**
                         * property
                         * transferStatus 0-待移交 2-已移交
                         */
                        Property property = new Property();
                        PropertyVo propertyVo = propertyMapper.selectPropertyVoByPno(dtl.getPno());
                        if (propertyVo != null) {
                            BeanUtil.copyProperties(propertyVo, property);
                            property.setTransferStatus("2");
                            if (StringUtils.isNotEmpty(add.getStoreId())) {
                                property.setBelongDeptId(storeMapper.selectStoreVoByID(add.getStoreId()).getDeptId());
                            } else {
                                property.setBelongDeptId(deptMapper.selectVoById(LoginHelper.getDeptId()).getParentId());
                            }
                            propertyMapper.updateById(property);
                        }

                        break;
                    case "2":
                        /**
                         * 处置类型
                         */
                        if (StringUtils.isNotEmpty(add.getDealType())) {
                            dtl.setDealType(add.getDealType());
                        }


                        InventoryVo inventoryVo = inventoryMapper.selectInventoryVoByPno(dtl.getPno());

                        /**
                         * 生成处置审核单
                         */

                        Deal dealAdd = dealMapper.selectDealVoByNo(item.getPno(), add.getId());


                        /**
                         * 判断当前为处置确认的处置申请，原处置单状态改为已确认
                         * 非处置确认单，按原先流程处理
                         */
                        if (bo.getDealIds() != null && bo.getDealIds().size() > 0) {
                            Deal updateEnty = new Deal();
                            updateEnty.setIsAck("1");
                            updateEnty.setAcker(LoginHelper.getNickname());
                            updateEnty.setAckTime(new Date());
                            updateEnty.setTaskId(add.getId());
                            dealMapper.update(updateEnty, new LambdaQueryWrapper<Deal>().in(Deal::getId, bo.getDealIds()));
                        }
                        //
                        if (dealAdd != null && dealAdd.getSource().equals("1")) {
                            dealAdd.setIsAck("1");
                            dealAdd.setAcker(LoginHelper.getNickname());
                            dealAdd.setAckTime(new Date());
                            dealAdd.setTaskId(add.getId());
                            dealMapper.updateById(dealAdd);
                        } else {
                            dealAdd = new Deal();
                            dealAdd.setId(IdUtil.simpleUUID());
                            dealAdd.setTaskId(add.getId());
                            dealAdd.setStatus("0");
                            dealAdd.setDelFlag("0");
                            dealAdd.setIsFinish("0");//挑拣状态
                            dealAdd.setIsSign("0");//签收状态

                            dealAdd.setDealNo(dtl.getPno());
                            dealAdd.setDeptId(dtl.getDeptId());
                            dealAdd.setDealType(add.getDealType());
                            dealAdd.setNums(dtl.getNums());
                            dealAdd.setIsCheck("1");
                            dealAdd.setStoreId(add.getStoreId());
                            dealAdd.setMemo(add.getRemark());
                            dealAdd.setIsAck("1");
                            dealAdd.setSource("0");//0-默认 1-推送
                            dealMapper.insert(dealAdd);

                            DealDtl dealDtlAdd = new DealDtl();
                            BeanUtil.copyProperties(dealAdd, dealDtlAdd);
                            dealDtlAdd.setId(IdUtil.simpleUUID());
                            dealDtlAdd.setDealId(dealAdd.getId());
                            dealDtlAdd.setAreaId(inventoryVo != null ? inventoryVo.getAreaId() : null);
                            dealDtlAdd.setLocatorId(inventoryVo != null ? inventoryVo.getLocatorId() : null);
                            dealDtlAdd.setPno(dealAdd.getDealNo());
                            dealDtlAdd.setName(dtl.getName());
                            dealDtlAdd.setHandleUnitName(deptMapper.selectVoById(bo.getDeptId()).getDeptName());//处置单位
                            dealDtlMapper.insert(dealDtlAdd);
                        }

                        break;
                }
                /**
                 * 物品日志
                 */
                String info = JsonUtils.toJsonString(dtl);
                String logContent = finalContent + "：(物品编号：" + item.getPno() + "，物品名称：" + item.getName() + "，申请说明：" + (StringUtils.isNotEmpty(add.getRemark()) ? add.getRemark() : "") + ")";
                commonService.savePropertyLog(dtl.getPno(), add.getId(), dtl.getName(), finalLogType, logContent, dtl.getDeptId(), info, add.getStoreId(), dtl.getNums(), null);

                return dtl;
            }).collect(Collectors.toList());
        }
        Long nums = 0L;
        if (dtls.size() > 0) {
            taskDtlMapper.insertBatch(dtls);
            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();
        }
        add.setNums(nums);//设置物品总数

        /**
         * 附件
         */
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            String finalBuss = ossBuss;
            bo.getOss().stream().forEach(oss -> {
                oss.setBuss(finalBuss);
                oss.setObjid(add.getId());
                sysOssMapper.updateById(oss);
            });
        }
        boolean flag = baseMapper.insert(add) > 0;

        List<OperatorLog> oplogs = new ArrayList<>();
        if (flag) {
            oplogs.add(commonService.saveOperatorLog(add.getId(), "oms", content));//操作日志

            /**
             * 新订单提醒
             */
            if (storeVo != null) {
                String phone = configService.selectConfigByKey("app.oms.dispatch.phone");
                SmsRequest smsRequest = new SmsRequest();
                if (bo.getType().equals("2")) {
                    smsRequest.setTemplateCode(SmsTemplateCode.DISPOSAL_NOTICE.getSMS_CODE());
                    SmsTemplateParam templateParam = new SmsTemplateParam();
                    templateParam.setArea(deptMapper.getAreaName(bo.getDeptId()));
                    smsRequest.setTemplateParam(templateParam);
                    smsRequest.setPhoneNumber(phone);
                    aliyunSmsService.AliyunSmsSend(smsRequest);

                    String dealPhone = configService.selectConfigByKey("app.oms.deal.phone");
                    if (!StringUtils.isEmpty(dealPhone)) {
                        smsRequest.setPhoneNumber(dealPhone);
                        aliyunSmsService.AliyunSmsSend(smsRequest);
                    }
                } else {
//                    smsRequest.setTemplateCode(SmsTemplateCode.TASK_NOTICE.getSMS_CODE());
//                    smsRequest.setPhoneNumber(phone);
//                    SmsTemplateParam templateParam = new SmsTemplateParam();
//                    templateParam.setOrderType(orderType);
//                    smsRequest.setTemplateParam(templateParam);
//                    AliyunSmsUtils.AliyunSmsSend(smsRequest);

                    /**
                     * 调度员
                     */
                    if (add.getDelivery().equals("0") && add.getType().equals("0")) {
                        SmsRequest dSmsRequest = new SmsRequest();
                        if (StringUtils.isNotBlank(phone)) {
                            dSmsRequest.setTemplateCode(SmsTemplateCode.TASK_NOTICE.getSMS_CODE());
                            dSmsRequest.setPhoneNumber(phone);
                            SmsTemplateParam dTemplateParam = new SmsTemplateParam();
                            dTemplateParam.setOrderType(orderType);
                            dTemplateParam.setOrderCode(add.getTaskNo());
                            dTemplateParam.setArea(deptMapper.getAreaName(bo.getDeptId()));
                            dSmsRequest.setTemplateParam(dTemplateParam);
                            aliyunSmsService.AliyunSmsSend(dSmsRequest);
                        }
                    }
                }

            }
        }

        //数据推送
        if (add.getSource().equals("0") && StringUtils.isNotEmpty(add.getType())) {
            TaskVo vo = baseMapper.selectTaskVoByID(add.getId());
            switch (add.getType()) {
                case "0":
                    InTaskDatasVo data = BeanUtil.toBean(vo, InTaskDatasVo.class);
                    List<InTaskDatasDtlVo> items = dtls.stream().map(item -> {
                        InTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, InTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    data.setItems(items);
                    data.setLogs(oplogs);
                    PushDatasUtil.pushInTaskDatas(data);
                    break;
                default:
                    OutTaskDatasVo outData = BeanUtil.toBean(vo, OutTaskDatasVo.class);
                    List<OutTaskDatasDtlVo> outItems = dtls.stream().map(item -> {
                        OutTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, OutTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    outData.setItems(outItems);
                    outData.setLogs(oplogs);
                    PushDatasUtil.pushOutTaskDatas(outData);
                    break;
            }
        }
        TaskVo vo = new TaskVo();
        BeanUtil.copyProperties(add, vo);
        return vo;
    }

    @Override
    public TaskVo insertTransferTaskBo(TaskBo bo) {

        TaskVo vo = new TaskVo();
        Task add = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(add);

        String head = "R";
        String ossBuss = "oms_warehouse";
        String logType = PropertyLogType.WAREHOUSE_DEVOLVE_TASK.getCode();
        String content = PropertyLogType.WAREHOUSE_DEVOLVE_TASK.getInfo();

        /**
         * 默认配置
         */
        add.setId(IdUtil.simpleUUID());
        add.setStatus("0");
        add.setDelFlag("0");
        add.setXzType(bo.getXzType());
        /**
         * 下发状态
         */
        add.setSendStatus("0");
        add.setSendReStatus("0");

        add.setTaskNo(getNo(head));//设置编号
        List<TaskDtl> dtls = new ArrayList<>();
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            String finalContent = content;
            String finalLogType = logType;
            dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl);
                dtl.setId(IdUtil.simpleUUID());
                dtl.setTaskId(add.getId());
                dtl.setDelFlag("0");
                dtl.setStatus("0");

                Property property = new Property();
                PropertyVo propertyVo = propertyMapper.selectPropertyVoByPno(dtl.getPno());
                if (propertyVo != null) {
                    BeanUtil.copyProperties(propertyVo, property);
                    property.setBelongDeptId(deptMapper.selectVoById(LoginHelper.getDeptId()).getParentId());//变更保管单位
                    propertyMapper.updateById(property);
                }
                /**
                 * 物品日志
                 */
                String info = JsonUtils.toJsonString(dtl);
                String logContent = finalContent + "：(物品编号：" + item.getPno() + "，物品名称：" + item.getName() + "，申请说明：" + (StringUtils.isNotEmpty(add.getRemark()) ? add.getRemark() : "") + ")";
                commonService.savePropertyLog(dtl.getPno(), add.getId(), dtl.getName(), finalLogType, logContent, dtl.getDeptId(), info, add.getStoreId(), dtl.getNums(), null);

                return dtl;
            }).collect(Collectors.toList());
        }

        Long nums = 0L;
        if (dtls.size() > 0) {
            taskDtlMapper.insertBatch(dtls);
            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();
        }
        add.setNums(nums);//设置物品总数

        /**
         * 附件
         */
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            bo.getOss().stream().forEach(oss -> {
                oss.setBuss(ossBuss);
                oss.setObjid(add.getId());
                sysOssMapper.updateById(oss);
            });
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            BeanUtil.copyProperties(add, vo);
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskVo insertReturnTaskBo(TaskBo bo) {

        String[] ignoreProperties = {"id", "createBy", "createTime", "updateBy", "updateTime"};
        TaskVo vo = new TaskVo();
        if (StringUtils.isEmpty(bo.getId())) {
            throw new ServiceException("参数异常");
        }
        Task task = baseMapper.selectById(bo.getId());
        Task add = new Task();
        BeanUtil.copyProperties(task, add, ignoreProperties);
        validEntityBeforeSave(add);
        add.setId(IdUtil.simpleUUID());
        add.setType("0");
        add.setStatus("0");
        add.setSendStatus("0");
        add.setSendReStatus("0");
        add.setTaskNo(getNo("R"));
        add.setCheckStatus(null);
        add.setChecker(null);
        add.setCheckTime(null);
        add.setReturnId(bo.getId());
        add.setSource("0");
        add.setReturnStatus("2");
        add.setDelivery(bo.getDelivery());
        add.setPropertyType(bo.getPropertyType());

        Long nums = 0L;
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            for (TaskDtlVo item : bo.getItems()) {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl);
                dtl.setId(IdUtil.simpleUUID());
                dtl.setTaskId(add.getId());
                taskDtlMapper.insert(dtl);

                nums += dtl.getNums();
            }
        }
        add.setNums(nums);
        boolean flag = baseMapper.insert(add) > 0;

        if (bo.getRevertMold().equals("1")) {
            task.setReturnStatus("1");//部分归还
        } else {
            task.setReturnStatus("2");//全部归还
        }

        if (bo.getOss() != null && bo.getOss().size() > 0) {
            bo.getOss().stream().forEach(item -> {
                item.setObjid(bo.getId());
                item.setBuss("return_task");
                sysOssMapper.updateById(item);
            });
        }

        baseMapper.updateById(task);//更新为已归还
        List<OperatorLog> oplogs = new ArrayList<>();
        List<TaskDtlVo> dtls = new ArrayList<>();
        if (flag) {
            BeanUtil.copyProperties(add, vo);
            TaskDtlBo dtlBo = new TaskDtlBo();
            dtlBo.setTaskId(vo.getId());
            dtls = taskDtlMapper.selectTaskDtlList(dtlBo);
            if (dtls != null && dtls.size() > 0) {
                vo.setItems(dtls);
            }

            /**
             * 操作日志
             */
            oplogs.add(commonService.saveOperatorLog(add.getId(), "oms", PropertyLogType.WAREHOUSE_TASK.getInfo()));

        }

        //数据推送
        if (add.getSource().equals("0") && StringUtils.isNotEmpty(add.getType())) {
            switch (add.getType()) {
                case "0":
                    InTaskDatasVo data = BeanUtil.toBean(vo, InTaskDatasVo.class);
                    List<InTaskDatasDtlVo> items = dtls.stream().map(item -> {
                        InTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, InTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    data.setItems(items);
                    data.setLogs(oplogs);
                    PushDatasUtil.pushInTaskDatas(data);
                    break;
                default:
                    OutTaskDatasVo outData = BeanUtil.toBean(vo, OutTaskDatasVo.class);
                    List<OutTaskDatasDtlVo> outItems = dtls.stream().map(item -> {
                        OutTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, OutTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    outData.setItems(outItems);
                    outData.setLogs(oplogs);
                    PushDatasUtil.pushOutTaskDatas(outData);
                    break;
            }
        }


        return vo;
    }

    /**
     * 修改出入库订单
     *
     * @param bo 出入库订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBoV2(TaskBo bo) {

        Task update = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(update);

        //订单类型
        String taskType = "";
        //流转日志内容
        String operatorContent = "";
        //财物日志类型
        String logType = "";

        if (StringUtils.isNotEmpty(update.getType())) {
            switch (update.getType()) {
                case "0":
                    taskType = "oms_warehouse";
                    operatorContent = "修改入库申请";
                    logType = "1";
                    break;
                case "1":
                    taskType = "oms_exWarehouse";
                    operatorContent = "修改出库申请";
                    logType = "2";
                    break;
                case "3":
                    taskType = "oms_transfer";
                    break;
                default:
                    break;
            }
        }

        Long nums = 0L;
        List<TaskDtl> dtls = new ArrayList<>();
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            List<Box> boxes = new ArrayList<>();
            dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = taskDtlMapper.selectById(item.getId());
                if (dtl == null) {
                    dtl = new TaskDtl();
                    BeanUtil.copyProperties(item, dtl, "id");
                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setTaskId(update.getId());
                    dtl.setDelFlag("0");
                    dtl.setStatus("0");

                    //财物处置方式
                    if (update.getType().equals("2")) {
                        dtl.setDealType(update.getDealType());

                        //附件
                        if (item.getOss() != null && item.getOss().size() > 0) {
                            for (SysOss oss : bo.getOss()) {
                                oss.setBuss("dealDtl");
                                oss.setObjid(item.getId());
                                sysOssMapper.updateById(oss);
                            }
                        }
                    }

                } else {
                    BeanUtil.copyProperties(item, dtl);
                }

                //箱号设置
                //判断是否是扫码箱子，或者是手动输入
                Box box = null;
                if (StringUtils.isNotEmpty(dtl.getBoxId())) {
                    box = boxMapper.selectById(dtl.getBoxId());
                    //箱子所在部门与申请账号部门不一致时，变更箱子所在部门为当前账号部门
                    if (box.getDeptId() != null && (!box.getDeptId().equals(LoginHelper.getDeptId()))) {
                        box.setDeptId(LoginHelper.getDeptId());
                    }
                    if (box.getStatus().equals("0")) {
                        //设置为已使用
                        box.setStatus("1");
                    }
                    boxMapper.insertOrUpdate(box);
                } else {
                    //手动输入箱号
                    if (StringUtils.isNotEmpty(dtl.getBoxNo())) {
                        box = boxMapper.selectOne(new LambdaQueryWrapper<Box>().eq(Box::getBoxNo, dtl.getBoxNo()));
                        if (box == null) {
                            box = new Box();
                            box.setId(IdUtil.simpleUUID());
                            box.setBoxNo(dtl.getBoxNo());
                            box.setDeptId(LoginHelper.getDeptId());
                            box.setCreateDept(LoginHelper.getDeptId());
                            box.setDelFlag("0");
                            box.setStatus("1");
                            boxMapper.insert(box);
                        }
                        //箱子所在部门与申请账号部门不一致时，变更箱子所在部门为当前账号部门
                        if (box.getDeptId() != null && (!box.getDeptId().equals(LoginHelper.getDeptId()))) {
                            box.setDeptId(LoginHelper.getDeptId());
                        }
                        if (box.getStatus().equals("0")) {
                            //设置为已使用
                            box.setStatus("1");
                        }
                        boxMapper.insertOrUpdate(box);
                    }
                }

                if (box != null) {
                    dtl.setBoxId(box.getId());
                    if (!boxes.contains(box)) {
                        boxes.add(box);
                    }
                }

                return dtl;
            }).collect(Collectors.toList());

            //箱子使用记录
            if (boxes != null && boxes.size() > 0) {
                for (Box box : boxes) {
                    BoxDept boxDept = new BoxDept();
                    boxDept.setId(IdUtil.simpleUUID());
                    boxDept.setBoxId(box.getId());
                    boxDept.setBoxNo(box.getBoxNo());
                    boxDept.setBoxDept(box.getDeptId());
                    boxDept.setStatus("1");
                    boxDept.setDelFlag("0");
                    boxDeptMapper.insert(boxDept);
                }
            }

            //计算财物数量
            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();

        }
        if (update.getNums() == null || nums != 0l) {
            update.setNums(nums);
        }

        if (dtls != null && dtls.size() > 0) {
            taskDtlMapper.insertOrUpdateBatch(dtls);
        }

        //附件
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            for (SysOss oss : bo.getOss()) {
                oss.setBuss(taskType);
                oss.setObjid(update.getId());
                sysOssMapper.updateById(oss);
            }
        }

        //判断是否再次下发
        if (StringUtils.isNotEmpty(bo.getAction())) {
            switch (bo.getAction()) {
                case "update":
                    if (update.getSendStatus().equals("1")) {
                        update.setSendReStatus("0");
                    }
                    break;
                case "sendsTask":
                    update.setSendReStatus(bo.getSendReStatus());
                    break;
                default:
                    break;
            }
        }

        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            List<OperatorLog> oplogs = new ArrayList<>();
            //操作日志
            oplogs.add(addOperatorLog(update.getId(), "oms", operatorContent));
            //数据推送
            if (flag && update.getSource().equals("0") && StringUtils.isNotEmpty(update.getType())) {
                TaskVo vo = baseMapper.selectTaskVoByID(update.getId());
                OperatorLogBo logBo = new OperatorLogBo();
                logBo.setObjid(update.getId());
                logBo.setLogType("oms");
//                List<OperatorLogVo> inlogs = logMapper.selectOperatorLogList(logBo);
                switch (update.getType()) {
                    case "0":
                        InTaskDatasVo data = BeanUtil.toBean(vo, InTaskDatasVo.class);
                        List<InTaskDatasDtlVo> items = dtls.stream().map(item -> {
                            InTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, InTaskDatasDtlVo.class);
                            return dvo;
                        }).collect(Collectors.toList());
                        data.setItems(items);
                        data.setLogs(oplogs);
                        PushDatasUtil.pushInTaskDatas(data);
                        break;
                    default:
                        OutTaskDatasVo outData = BeanUtil.toBean(vo, OutTaskDatasVo.class);
                        List<OutTaskDatasDtlVo> outItems = dtls.stream().map(item -> {
                            OutTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, OutTaskDatasDtlVo.class);
                            return dvo;
                        }).collect(Collectors.toList());
                        outData.setItems(outItems);
                        outData.setLogs(oplogs);
                        PushDatasUtil.pushOutTaskDatas(outData);
                        break;
                }
            }
        }

        return flag;
    }

    /**
     * 修改出入库订单
     *
     * @param bo 出入库订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(TaskBo bo) {

        Task update = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(update);
        List<TaskDtl> dtls = new ArrayList<>();
        List<TaskDtl> dels = new ArrayList<>();
        Long nums = 0l;
        String buss = "";
        if (StringUtils.isNotEmpty(update.getType())) {
            switch (update.getType()) {
                case "0":
                    buss = "warehouseDtl";
                    break;
                case "1":
                    buss = "exWarehouseDtl";
                    break;
                case "2":
                    buss = "dealDtl";
                    break;
                case "3":
                    buss = "transferDtl";
                    break;
                default:
                    break;
            }
        }

        if (bo.getItems() != null && bo.getItems().size() > 0) {
            for (TaskDtlVo item : bo.getItems()) {
                TaskDtl dtl = BeanUtil.toBean(item, TaskDtl.class);

                LambdaQueryWrapper<TaskDtl> lqw = Wrappers.lambdaQuery();
                lqw.eq(StringUtils.isNotBlank(update.getId()), TaskDtl::getTaskId, update.getId());
                lqw.eq(StringUtils.isNotBlank(item.getPno()), TaskDtl::getPno, item.getPno());
                TaskDtl taskDtl = taskDtlMapper.selectOne(lqw);

                if (StringUtils.isEmpty(item.getId()) && taskDtl == null) {
                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setDelFlag("0");
                    dtl.setTaskId(update.getId());
                } else {
                    dtl.setId(taskDtl.getId());
                }
                dtl.setNums(item.getNums() == null ? 1L : item.getNums());

                if (item.getOss() != null && item.getOss().size() > 0) {
                    for (SysOss oss : item.getOss()) {
                        oss.setBuss(buss);
                        oss.setObjid(dtl.getId());
                        sysOssMapper.updateById(oss);
                    }
                }

                if (dtl.getDelFlag().equals("0")) {
                    nums += dtl.getNums();
                    dtls.add(dtl);
                } else {
                    dels.add(dtl);
                }
            }
            update.setNums(nums);
        }

        taskDtlMapper.insertOrUpdateBatch(dtls);
        if (dels != null && dels.size() > 0) {
            taskDtlMapper.deleteBatchIds(dels);
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 订单编辑
     *
     * @param bo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTaskBo(TaskBo bo) {

        Task task = baseMapper.selectById(bo.getId());

        Task update = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(update);

        if (
                !StringUtils.isEmpty(task.getCheckStatus())
                        && !task.getCheckStatus().equals("2")
                        && !StringUtils.isEmpty(bo.getCheckStatus())
                        && bo.getCheckStatus().equals("2")
        ) {
            update.setDispatcherId(LoginHelper.getUserId());
        }

        Long nums = update.getNums();
        String ossBuss = null;
        String content = null;

        /**
         * 已下发申请单，重新下发
         * sendStatus 下发状态 0-待下发 1-已下发
         * sendReStatus 重新下发状态 0-待下发 1-已下发
         */
        if (update.getSendStatus().equals("1")) {
            update.setSendReStatus("0");
        }

        /**
         * type
         * 0-入库 1-出库 2-处置 3-调用
         */
        switch (update.getType()) {
            case "0":
                ossBuss = "oms_warehouse";
                content = "修改入库申请";
                break;
            case "2":
                ossBuss = "oms_deal";
                content = "修改处置申请";
                /**
                 * 处置申请
                 * 发还申请 dealType-3返回当事人
                 * 从发还申请提交的申请单 back
                 */
                if (StringUtils.isNotEmpty(bo.getSubmitType()) && bo.getSubmitType().equals("back") && bo.getDealType().equals("3")) {

                    TaskBo info = new TaskBo();
                    info.setPolice(bo.getPolice());
                    info.setPoliceTel(bo.getPoliceTel());
                    info.setBacker(bo.getBacker());
                    info.setBackTel(bo.getBackTel());
                    info.setBackCard(bo.getBackCard());
                    //身份证附件
                    if (bo.getBackOss() != null && bo.getBackOss().size() > 0) {
                        for (SysOss oss : bo.getBackOss()) {
                            oss.setObjid(update.getId());
                            oss.setBuss("backDeal");
                            sysOssMapper.updateById(oss);
                        }
                    }
                    update.setInfo(JsonUtils.toJsonString(info));
                } else if (bo.getDelivery().equals("1")) {//非发还申请，是自行配送
                    TaskBo info = new TaskBo();
                    info.setPickuper(bo.getPickuper());
                    info.setPickupTel(bo.getPickupTel());
                    info.setPickupCardType(bo.getPickupCardType());
                    info.setPickupCard(bo.getPickupCard());
                    update.setInfo(JsonUtils.toJsonString(info));
                }

                break;
            default:
                if (update.getType().equals("1")) {
                    ossBuss = "oms_exWarehouse";
                    content = "修改出库申请";
                } else if (update.getType().equals("3")) {
                    ossBuss = "oms_transfer";
                    content = "修改调用申请";
                }
                /**
                 * 已审核
                 */
                if (!update.getCheckStatus().equals("0")) {
                    update.setChecker(LoginHelper.getNickname());
                    update.setCheckTime(new Date());
                }
                /**
                 * 审核不通过，编辑后可重新审核
                 * 重新审核标签 update
                 */
                if (update.getCheckStatus().equals("2") && StringUtils.isNotEmpty(bo.getSubmitType()) && bo.getSubmitType().equals("update")) {
                    update.setCheckStatus("0");//重新审核
                }

                break;
        }

        if (bo.getDelivery().equals("1")) {
            switch (bo.getType()) {
                case "0":
                    break;
                case "2":
                    break;
                default:
                    TaskBo info = new TaskBo();
                    info.setPickuper(bo.getPickuper());
                    info.setPickupTel(bo.getPickupTel());
                    info.setPickupCardType(bo.getPickupCardType());
                    info.setPickupCard(bo.getPickupCard());
                    update.setInfo(JsonUtils.toJsonString(info));
                    break;
            }
        }

        /**
         * 查询原明细数据
         */
        TaskDtlBo dtlBo = new TaskDtlBo();
        dtlBo.setTaskId(update.getId());
        List<TaskDtlVo> olds = taskDtlMapper.selectTaskDtlList(dtlBo);

        DealBo dealBo = new DealBo();
        dealBo.setTaskId(update.getId());
        List<DealVo> dealOlds = dealMapper.selectDealList(dealBo);

        List<TaskDtl> dtls = new ArrayList<>();

        if (bo.getItems() != null && bo.getItems().size() > 0) {
            dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl);
                if (StringUtils.isEmpty(dtl.getId())) {//修改后的物品
                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setDelFlag("0");
                    dtl.setStatus("0");
                    dtl.setTaskId(update.getId());

                    if (update.getType().equals("2")) {
                        /**
                         * 处置类型
                         */
                        if (StringUtils.isNotEmpty(update.getDealType())) {
                            dtl.setDealType(update.getDealType());
                        }


                        InventoryVo inventoryVo = inventoryMapper.selectInventoryVoByPno(dtl.getPno());

                        /**
                         * 生成处置审核单
                         */

                        Deal dealAdd = new Deal();
                        dealAdd.setId(IdUtil.simpleUUID());
                        dealAdd.setTaskId(update.getId());
                        dealAdd.setStatus("0");
                        dealAdd.setDelFlag("0");
                        dealAdd.setIsFinish("0");//挑拣状态
                        dealAdd.setIsSign("0");//签收状态

                        dealAdd.setDealNo(dtl.getPno());
                        dealAdd.setDeptId(dtl.getDeptId());
                        dealAdd.setDealType(update.getDealType());
                        dealAdd.setNums(dtl.getNums());
                        dealAdd.setIsCheck("0");
                        dealAdd.setStoreId(update.getStoreId());
                        dealAdd.setMemo(update.getRemark());
                        dealMapper.insert(dealAdd);

                        DealDtl dealDtlAdd = new DealDtl();
                        BeanUtil.copyProperties(dealAdd, dealDtlAdd);
                        dealDtlAdd.setId(IdUtil.simpleUUID());
                        dealDtlAdd.setDealId(dealAdd.getId());
                        dealDtlAdd.setAreaId(inventoryVo != null ? inventoryVo.getAreaId() : null);
                        dealDtlAdd.setLocatorId(inventoryVo != null ? inventoryVo.getLocatorId() : null);
                        dealDtlAdd.setPno(dealAdd.getDealNo());
                        dealDtlAdd.setName(dtl.getName());
                        dealDtlAdd.setHandleUnitName(deptMapper.selectVoById(bo.getDeptId()).getDeptName());//处置单位
                        dealDtlMapper.insert(dealDtlAdd);
                    } else if (update.getType().equals("0")) {
                        /**
                         * property
                         * transferStatus 0-待移交 2-已移交
                         */
                        Property property = new Property();
                        PropertyVo propertyVo = propertyMapper.selectPropertyVoByPno(dtl.getPno());
                        if (propertyVo != null) {
                            BeanUtil.copyProperties(propertyVo, property);
                            if (!property.getTransferStatus().equals("2")) {
                                property.setTransferStatus("2");
                                if (StringUtils.isNotEmpty(update.getStoreId())) {
                                    property.setBelongDeptId(storeMapper.selectStoreVoByID(update.getStoreId()).getDeptId());
                                } else {
                                    property.setBelongDeptId(deptMapper.selectVoById(LoginHelper.getDeptId()).getParentId());
                                }
                                propertyMapper.updateById(property);
                            }
                        }
                    }
                }
                /**
                 * 迭代查询移除的明细
                 */
                Iterator iterator = olds.iterator();
                while (iterator.hasNext()) {
                    TaskDtlVo taskDtl = (TaskDtlVo) iterator.next();
                    if (taskDtl.getId().equals(dtl.getId())) {
                        iterator.remove();
                    }
                }
                Iterator dIterator = dealOlds.iterator();
                while (dIterator.hasNext()) {
                    DealVo deal = (DealVo) dIterator.next();
                    if (deal.getDealNo().equals(dtl.getPno())) {
                        dIterator.remove();
                    }
                }


                return dtl;
            }).collect(Collectors.toList());

            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();
        }
        update.setNums(nums);

        if (dtls.size() > 0) {
            taskDtlMapper.insertOrUpdateBatch(dtls);
        }
        //已删除的物品处理：删除dtl表、回退可移交状态
        if (olds != null && olds.size() > 0) {
            olds.forEach(item -> {
                Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, item.getPno()));
                property.setTransferStatus("0");//退回可移交状态
                propertyMapper.updateById(property);

                taskDtlMapper.deleteByDtlId(item.getId());
            });
        }
        if (dealOlds != null && dealOlds.size() > 0) {
            dealOlds.forEach(item -> {
                if (item.getIsCheck().equals("1")) {
                    throw new ServiceException("检测到您变更的物品里存在已审核物品，请确认后重新提交！");
                }
                dealMapper.deleteWithDealDtlById(item.getId());
            });
        }
        /**
         * 附件
         */
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            String finalOssBuss = ossBuss;
            bo.getOss().stream().forEach(oss -> {
                oss.setBuss(finalOssBuss);
                oss.setObjid(update.getId());
                sysOssMapper.updateById(oss);
            });
        }
        boolean flag = baseMapper.updateById(update) > 0;
        List<OperatorLog> oplogs = new ArrayList<>();
        if (flag) {
            /**
             * 操作日志
             */
            oplogs.add(commonService.saveOperatorLog(update.getId(), "oms", content));
        }

        //数据推送
        if (StringUtils.isNotEmpty(update.getType())) {
            TaskVo vo = baseMapper.selectTaskVoByID(update.getId());
            switch (update.getType()) {
                case "0":
                    InTaskDatasVo data = BeanUtil.toBean(vo, InTaskDatasVo.class);
                    List<InTaskDatasDtlVo> items = dtls.stream().map(item -> {
                        InTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, InTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    data.setItems(items);
                    data.setLogs(oplogs);
                    PushDatasUtil.pushInTaskDatas(data);
                    break;
                default:
                    OutTaskDatasVo outData = BeanUtil.toBean(vo, OutTaskDatasVo.class);
                    List<OutTaskDatasDtlVo> outItems = dtls.stream().map(item -> {
                        OutTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, OutTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    outData.setItems(outItems);
                    outData.setLogs(oplogs);
                    PushDatasUtil.pushOutTaskDatas(outData);
                    break;
            }
        }

        return flag;
    }

    /**
     * 订单更新
     *
     * @param bo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTaskEnty(TaskBo bo) {

        Task update = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(update);

        /**
         * 处置清单
         */
        if (bo.getDealsOss() != null && bo.getDealsOss().size() > 0) {
            for (SysOss oss : bo.getDealsOss()) {
                oss.setBuss("dealsForm");
                oss.setObjid(update.getId());
                sysOssMapper.updateById(oss);
            }
        }

        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean finishTaskEnty(TaskBo bo) {

        Task update = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(update);

        TaskDtlBo dtlBo = new TaskDtlBo();
        dtlBo.setTaskId(update.getId());
        List<TaskDtl> dtls = taskDtlMapper.selectTaskDtl(dtlBo);

        boolean flag = baseMapper.updateById(update) > 0;
        List<OperatorLog> oplogs = new ArrayList<>();
        if (flag) {
            /**
             * 操作日志
             */
            oplogs.add(commonService.saveOperatorLog(update.getId(), "oms", "签收"));
        }

        //数据推送
        if (StringUtils.isNotEmpty(update.getType())) {
            TaskVo vo = baseMapper.selectTaskVoByID(update.getId());
            switch (update.getType()) {
                case "0":
                    InTaskDatasVo data = BeanUtil.toBean(vo, InTaskDatasVo.class);
                    List<InTaskDatasDtlVo> items = dtls.stream().map(item -> {
                        InTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, InTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    data.setItems(items);
                    data.setLogs(oplogs);
                    PushDatasUtil.pushInTaskDatas(data);
                    break;
                default:
                    OutTaskDatasVo outData = BeanUtil.toBean(vo, OutTaskDatasVo.class);
                    List<OutTaskDatasDtlVo> outItems = dtls.stream().map(item -> {
                        OutTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, OutTaskDatasDtlVo.class);
                        return dvo;
                    }).collect(Collectors.toList());
                    outData.setItems(outItems);
                    outData.setLogs(oplogs);
                    PushDatasUtil.pushOutTaskDatas(outData);
                    break;
            }
        }

        return flag;
    }

    @Override
    public Boolean returnTimeUpdate(TaskBo bo) {

        Task update = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;

        if (flag) {
            ExWarehouse exWarehouse = exWarehouseMapper.selectExWarehouseByTaskId(update.getId());
            exWarehouse.setReturnTime(bo.getReturnTime());
            flag = exWarehouseMapper.updateById(exWarehouse) > 0;

            String phone = configService.selectConfigByKey("app.oms.dispatch.phone");
            SmsRequest smsRequest = new SmsRequest();
            if (StringUtils.isNotBlank(phone)) {
                smsRequest.setTemplateCode(SmsTemplateCode.EXTEND_NOTICE.getSMS_CODE());
                smsRequest.setPhoneNumber(phone);
                SmsTemplateParam templateParam = new SmsTemplateParam();
                templateParam.setOrderCode(update.getTaskNo());
                templateParam.setArea(deptMapper.getAreaName(bo.getDeptId()));
                templateParam.setReturnDate(DateUtils.date2String(bo.getReturnTime(), "yyyy-MM-dd"));
                smsRequest.setTemplateParam(templateParam);
                aliyunSmsService.AliyunSmsSend(smsRequest);
            }
        }
        return flag;
    }

    /**
     * 保存原调用编号
     * 更新原申请相关的数据
     *
     * @param bo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean replaceTask(TaskBo bo) {

        String[] ignoreProperties = {"id", "createBy", "createTime", "updateBy", "updateTime"};
        Task task = baseMapper.selectById(bo.getId());
        Task update = new Task();
        BeanUtil.copyProperties(task, update, ignoreProperties);
        update.setReturnId(bo.getId());
        update.setTaskNo(getNo("C"));
        update.setReplaceNo(bo.getTaskNo());
        update.setType("2");
        long proTotalNumber =
                bo.getItems().stream().map(TaskDtlVo::getNums).mapToLong(Long::valueOf).sum();
        update.setNums(proTotalNumber);
        validEntityBeforeSave(update);

        if (baseMapper.insert(update) == 0) {
            throw new ServiceException("保存订单信息失败");
        }

        if (bo.getItems() != null && bo.getItems().size() > 0) {
            List<TaskDtl> dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl, ignoreProperties);
                dtl.setTaskId(update.getId());
                return dtl;
            }).collect(Collectors.toList());
            if (!taskDtlMapper.insertBatch(dtls)) {
                throw new ServiceException("保存处置财物失败");
            }
        } else {
            throw new ServiceException("无处置财物");
        }

        //add task disoisal info
        TaskDisposalInfo taskDisposalInfo = new TaskDisposalInfo();
        taskDisposalInfo.setTaskId(update.getId());
        taskDisposalInfo.setDisposalType(bo.getDealType());
        taskDisposalInfo.setAuthCenter(0);

        if (taskDisposalInfoMapper.insert(taskDisposalInfo) == 0) {
            throw new ServiceException("保存处置信息失败");
        }

        return true;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Task entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除出入库订单
     *
     * @param ids 需要删除的出入库订单主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {

        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithDtlByIds(TaskBo bo) {

        List<TaskDtl> dtls = new ArrayList<>();
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl);
                return dtl;
            }).collect(Collectors.toList());
        }

        //更新箱号
        if (bo.getBoxList() != null && bo.getBoxList().size() > 0) {
            Box box = boxMapper.selectById(bo.getBoxList().get(0).getId());
            box.setStatus("0");
            boxMapper.insertOrUpdate(box);

        }
        return taskDtlMapper.deleteBatchIds(dtls) > 0;
    }

    /**
     * 撤销
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithTask(String id, String cancelReason) {

        boolean flag = false;

        Task task = baseMapper.selectById(id);
        List<TaskDtl> dtlList = taskDtlMapper.selectList(new LambdaQueryWrapper<TaskDtl>().eq(TaskDtl::getTaskId, task.getId()));
        Warehouse warehouse = null;
        ExWarehouse exWarehouse = null;
        Order order = null;
        Waybill waybill = null;
        String orderId = null;
        List<Deal> dealList = new ArrayList<>();
        switch (task.getType()) {
            case "0":
                warehouse = warehouseMapper.selectWarehouseByTaskId(task.getId());

                /**
                 * 物品日志删除 propertylog
                 */
                if (StringUtils.isBlank(task.getReturnId())) {
                    dtlList.stream().forEach(item -> {
                        Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, item.getPno()));
                        property.setTransferStatus("0");//退回可移交状态
                        propertyMapper.updateById(property);
                        /**
                         * 删除除移交登记以外的物品日志记录
                         */
                        List<PropertyLog> plogs = propertyLogMapper.selectList(new LambdaQueryWrapper<PropertyLog>().eq(PropertyLog::getPno, item.getPno()).notIn(PropertyLog::getLogType, "0"));
                        if (plogs != null && plogs.size() > 0) {
                            propertyLogMapper.deleteBatchIds(plogs);
                        }
                    });
                }
                //归还单撤销 原调用单归还状态重置
                if (!StringUtils.isEmpty(task.getReturnId())) {
                    Task transTask = baseMapper.selectById(task.getReturnId());
                    if (transTask != null) {
                        transTask.setReturnStatus("0");//重置为待归还
                        baseMapper.updateById(transTask);
                    }
                }
                break;
            case "2":
                dealList = dealMapper.selectList(new LambdaQueryWrapper<Deal>().eq(Deal::getTaskId, task.getId()));
                exWarehouse = exWarehouseMapper.selectExWarehouseByTaskId(task.getId());
                break;
            default:
                exWarehouse = exWarehouseMapper.selectExWarehouseByTaskId(task.getId());
                break;
        }

        /**
         * 入库单撤销
         */
        if (ObjectUtils.isNotNull(warehouse) && StringUtils.isNotBlank(warehouse.getId())) {
            //上架任务
            PutTask putTask = putTaskMapper.selectOne(new LambdaQueryWrapper<PutTask>().eq(PutTask::getWid, warehouse.getId()));
            if (putTask != null) {
                List<PutDtl> putDtls = putDtlMapper.selectList(new LambdaQueryWrapper<PutDtl>().eq(PutDtl::getTaskId, putTask.getId()));
                if (putDtls != null && putDtls.size() > 0) {
                    putDtlMapper.deleteBatchIds(putDtls);
                }
                putTaskMapper.deleteById(putTask);
            }

            warehouseMapper.deleteById(warehouse);
            WarehouseDtlBo dtlBo = new WarehouseDtlBo();
            dtlBo.setWid(warehouse.getId());
            List<WarehouseDtl> dtls = warehouseDtlMapper.selectWarehouseDtl(dtlBo);
            if (dtls != null && dtls.size() > 0) {
                warehouseDtlMapper.deleteBatchIds(dtls);
            }

        }

        /**
         * 出库、处置、调用撤销
         */
        if (ObjectUtils.isNotNull(exWarehouse) && StringUtils.isNotBlank(exWarehouse.getId())) {
            /**
             * type 1-出库 2-处置 3-调用
             * 非处置单，完成挑拣后，不可撤销
             * 处置单，已做审核通过，不可撤销
             */
//            if(!exWarehouse.getType().equals("2")){
            PickVo pick = pickMapper.queryPickVoByExWarehouseID(exWarehouse.getId());
            //撤销挑拣
            if (pick != null) {
                List<PickDtl> pickDtls = pickDtlMapper.selectList(new LambdaQueryWrapper<PickDtl>().eq(PickDtl::getPickId, pick.getId()));
                pickMapper.deleteById(pick.getId());
                if (pickDtls != null && pickDtls.size() > 0) {
                    pickDtlMapper.deleteBatchIds(pickDtls);
                }
            }
//                if(pick.getStatus().equals("1")){
//                    throw new ServiceException("当前订单已挑拣，不可撤销！");
//                }

            exWarehouseMapper.deleteById(exWarehouse);
            ExWarehouseDtlBo dtlBo = new ExWarehouseDtlBo();
            dtlBo.setWid(exWarehouse.getId());
            List<ExWarehouseDtl> dtls = exWarehouseDtlMapper.selectExWarehouseDtl(dtlBo);
            if (dtls != null && dtls.size() > 0) {
                exWarehouseDtlMapper.deleteBatchIds(dtls);
            }

            List<PropertyLog> plogs = propertyLogMapper.selectList(new LambdaQueryWrapper<PropertyLog>().eq(PropertyLog::getObjid, exWarehouse.getId()));
            if (plogs != null && plogs.size() > 0) {
                propertyLogMapper.deleteBatchIds(plogs);
            }

//            }else {
//                throw new ServiceException("当前订单已审核通过，不可撤销！");
//            }
        }

        /**
         * 处置审核撤销
         */
        if (dealList != null && dealList.size() > 0) {
            dealList.forEach(deal -> {
                dealMapper.deleteById(deal);
                DealDtlBo dtlBo = new DealDtlBo();
                dtlBo.setDealId(deal.getId());
                List<DealDtl> dtls = dealDtlMapper.selectDealDtl(dtlBo);
                if (dtls != null && dtls.size() > 0) {
                    dealDtlMapper.deleteBatchIds(dtls);
                }

            });
        }

        order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getTaskId, task.getId()));

        /**
         * 物流配送撤销
         */
        if (ObjectUtils.isNotNull(order) && StringUtils.isNotBlank(order.getId())) {
            orderMapper.deleteById(order);
            OrderDtlBo dtlBo = new OrderDtlBo();
            dtlBo.setOrderId(order.getId());
            List<OrderDtl> dtls = orderDtlMapper.selectOrderDtlsByOrderId(dtlBo);
            if (dtls != null && dtls.size() > 0) {
                orderDtlMapper.deleteBatchIds(dtls);
            }
            List<OrderLog> logs = orderLogMapper.selectOrderLogsById(order.getId());
            if (logs != null && logs.size() > 0) {
                orderLogMapper.deleteBatchIds(logs);
            }
            orderId = order.getId();
        }

        if (StringUtils.isNotBlank(orderId)) {
            waybill = waybillMapper.selectWaybillByOrderId(orderId);
            if (ObjectUtils.isNotNull(waybill) && StringUtils.isNotBlank(waybill.getId())) {
                waybillMapper.deleteById(waybill);
                WaybillDtlBo dtlBo = new WaybillDtlBo();
                dtlBo.setWaybillId(waybill.getId());
                List<WaybillDtl> dtls = waybillDtlMapper.selectWaybillDtlsByWid(dtlBo);
                if (dtls != null && dtls.size() > 0) {
                    waybillDtlMapper.deleteBatchIds(dtls);
                }
                WaybillLogBo logBo = new WaybillLogBo();
                logBo.setTrackId(waybill.getId());
                List<WaybillLog> logs = waybillLogMapper.selectWaybillLogListByWid(logBo);
                if (logs != null && logs.size() > 0) {
                    waybillLogMapper.deleteBatchIds(logs);
                }
            }
        }

        /**
         * 操作日志删除 operatorlog
         */
        List<OperatorLog> oLogs = operatorLogMapper.selectList(new LambdaQueryWrapper<OperatorLog>().eq(OperatorLog::getObjid, id));
        if (oLogs != null && oLogs.size() > 0) {
            operatorLogMapper.deleteBatchIds(oLogs);
        }

        /**
         * 删除物品日志
         */
        List<PropertyLog> plogs = propertyLogMapper.selectList(new LambdaQueryWrapper<PropertyLog>().eq(PropertyLog::getObjid, task.getId()));
        if (plogs != null && plogs.size() > 0) {
            propertyLogMapper.deleteBatchIds(plogs);
        }

        flag = baseMapper.updateById(new Task(task.getId(), cancelReason)) > 0;
        flag = baseMapper.deleteById(task) > 0;
        flag = taskDtlMapper.deleteBatchIds(dtlList) > 0;

        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithTaskByAdmin(String id, String cancelReason) {

        boolean flag = false;

        Task task = baseMapper.selectById(id);
        List<TaskDtl> dtlList = taskDtlMapper.selectList(new LambdaQueryWrapper<TaskDtl>().eq(TaskDtl::getTaskId, task.getId()));
        Warehouse warehouse = null;
        ExWarehouse exWarehouse = null;
        Order order = null;
        Waybill waybill = null;
        String orderId = null;
        List<Deal> dealList = new ArrayList<>();
        switch (task.getType()) {
            case "0":
                warehouse = warehouseMapper.selectWarehouseByTaskId(task.getId());

                /**
                 * 物品日志删除 propertylog
                 */
                if (StringUtils.isBlank(task.getReturnId())) {
                    dtlList.stream().forEach(item -> {
                        Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, item.getPno()));
                        property.setTransferStatus("0");//退回可移交状态
                        propertyMapper.updateById(property);
                        /**
                         * 删除除移交登记以外的物品日志记录
                         */
                        List<PropertyLog> plogs = propertyLogMapper.selectList(new LambdaQueryWrapper<PropertyLog>().eq(PropertyLog::getPno, item.getPno()).notIn(PropertyLog::getLogType, "0"));
                        if (plogs != null && plogs.size() > 0) {
                            propertyLogMapper.deleteBatchIds(plogs);
                        }
                    });
                }
                //归还单撤销 原调用单归还状态重置
                if (!StringUtils.isEmpty(task.getReturnId())) {
                    Task transTask = baseMapper.selectById(task.getReturnId());
                    if (transTask != null) {
                        transTask.setReturnStatus("0");//重置为待归还
                        baseMapper.updateById(transTask);
                    }
                }
                break;
            case "2":
                dealList = dealMapper.selectList(new LambdaQueryWrapper<Deal>().eq(Deal::getTaskId, task.getId()));
                exWarehouse = exWarehouseMapper.selectExWarehouseByTaskId(task.getId());
                break;
            default:
                exWarehouse = exWarehouseMapper.selectExWarehouseByTaskId(task.getId());
                break;
        }

        /**
         * 入库单撤销
         */
        if (ObjectUtils.isNotNull(warehouse) && StringUtils.isNotBlank(warehouse.getId())) {
            //上架任务
            PutTask putTask = putTaskMapper.selectOne(new LambdaQueryWrapper<PutTask>().eq(PutTask::getWid, warehouse.getId()));
            if (putTask != null) {
                List<PutDtl> putDtls = putDtlMapper.selectList(new LambdaQueryWrapper<PutDtl>().eq(PutDtl::getTaskId, putTask.getId()));
                if (putDtls != null && putDtls.size() > 0) {
                    putDtlMapper.deleteBatchIds(putDtls);
                }
                putTaskMapper.deleteById(putTask);
            }
            warehouseMapper.deleteById(warehouse);
            WarehouseDtlBo dtlBo = new WarehouseDtlBo();
            dtlBo.setWid(warehouse.getId());
            List<WarehouseDtl> dtls = warehouseDtlMapper.selectWarehouseDtl(dtlBo);
            if (dtls != null && dtls.size() > 0) {
                warehouseDtlMapper.deleteBatchIds(dtls);
            }
        }

        /**
         * 出库、处置、调用撤销
         */
        if (ObjectUtils.isNotNull(exWarehouse) && StringUtils.isNotBlank(exWarehouse.getId())) {
            /**
             * type 1-出库 2-处置 3-调用
             * 非处置单，完成挑拣后，不可撤销
             * 处置单，已做审核通过，不可撤销
             */
//            if(!exWarehouse.getType().equals("2")){
            PickVo pick = pickMapper.queryPickVoByExWarehouseID(exWarehouse.getId());
//                if(pick.getStatus().equals("1")){
//                    throw new ServiceException("当前订单已挑拣，不可撤销！");
//                }
            //撤销挑拣
            if (pick != null) {
                List<PickDtl> pickDtls = pickDtlMapper.selectList(new LambdaQueryWrapper<PickDtl>().eq(PickDtl::getPickId, pick.getId()));
                pickMapper.deleteById(pick.getId());
                if (pickDtls != null && pickDtls.size() > 0) {
                    pickDtlMapper.deleteBatchIds(pickDtls);
                }
            }


            exWarehouseMapper.deleteById(exWarehouse);
            ExWarehouseDtlBo dtlBo = new ExWarehouseDtlBo();
            dtlBo.setWid(exWarehouse.getId());
            List<ExWarehouseDtl> dtls = exWarehouseDtlMapper.selectExWarehouseDtl(dtlBo);
            if (dtls != null && dtls.size() > 0) {
                exWarehouseDtlMapper.deleteBatchIds(dtls);
            }

            List<PropertyLog> plogs = propertyLogMapper.selectList(new LambdaQueryWrapper<PropertyLog>().eq(PropertyLog::getObjid, exWarehouse.getId()));
            if (plogs != null && plogs.size() > 0) {
                propertyLogMapper.deleteBatchIds(plogs);
            }

//            }else {
//                throw new ServiceException("当前订单已审核通过，不可撤销！");
//            }
        }

        /**
         * 处置审核撤销
         */
        if (dealList != null && dealList.size() > 0) {
            dealList.stream().forEach(deal -> {
                dealMapper.deleteById(deal);
                DealDtlBo dtlBo = new DealDtlBo();
                dtlBo.setDealId(deal.getId());
                List<DealDtl> dtls = dealDtlMapper.selectDealDtl(dtlBo);
                if (dtls != null && dtls.size() > 0) {
                    dealDtlMapper.deleteBatchIds(dtls);
                }

            });
        }

        order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getTaskId, task.getId()));

        /**
         * 物流配送撤销
         */
        if (ObjectUtils.isNotNull(order) && StringUtils.isNotBlank(order.getId())) {
            orderMapper.deleteById(order);
            OrderDtlBo dtlBo = new OrderDtlBo();
            dtlBo.setOrderId(order.getId());
            List<OrderDtl> dtls = orderDtlMapper.selectOrderDtlsByOrderId(dtlBo);
            if (dtls != null && dtls.size() > 0) {
                orderDtlMapper.deleteBatchIds(dtls);
            }
            List<OrderLog> logs = orderLogMapper.selectOrderLogsById(order.getId());
            if (logs != null && logs.size() > 0) {
                orderLogMapper.deleteBatchIds(logs);
            }
            orderId = order.getId();
        }

        if (StringUtils.isNotBlank(orderId)) {
            waybill = waybillMapper.selectWaybillByOrderId(orderId);
            if (ObjectUtils.isNotNull(waybill) && StringUtils.isNotBlank(waybill.getId())) {
                waybillMapper.deleteById(waybill);
                WaybillDtlBo dtlBo = new WaybillDtlBo();
                dtlBo.setWaybillId(waybill.getId());
                List<WaybillDtl> dtls = waybillDtlMapper.selectWaybillDtlsByWid(dtlBo);
                if (dtls != null && dtls.size() > 0) {
                    waybillDtlMapper.deleteBatchIds(dtls);
                }
                WaybillLogBo logBo = new WaybillLogBo();
                logBo.setTrackId(waybill.getId());
                List<WaybillLog> logs = waybillLogMapper.selectWaybillLogListByWid(logBo);
                if (logs != null && logs.size() > 0) {
                    waybillLogMapper.deleteBatchIds(logs);
                }
            }
        }

        /**
         * 操作日志删除 operatorlog
         */
        List<OperatorLog> oLogs = operatorLogMapper.selectList(new LambdaQueryWrapper<OperatorLog>().eq(OperatorLog::getObjid, id));
        if (oLogs != null && oLogs.size() > 0) {
            operatorLogMapper.deleteBatchIds(oLogs);
        }

        /**
         * 删除物品日志
         */
        List<PropertyLog> plogs = propertyLogMapper.selectList(new LambdaQueryWrapper<PropertyLog>().eq(PropertyLog::getObjid, task.getId()));
        if (plogs != null && plogs.size() > 0) {
            propertyLogMapper.deleteBatchIds(plogs);
        }

        flag = baseMapper.updateById(new Task(task.getId(), cancelReason)) > 0;
        flag = taskDtlMapper.deleteBatchIds(dtlList) > 0;

        return flag;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean restoreWithTask(String id) {

        boolean flag = false;

        Warehouse warehouse = null;
        ExWarehouse exWarehouse = null;
        List<Deal> dealList = new ArrayList<>();

        Task task = baseMapper.selectTaskEntity(id);

        task.setDelFlag("0");

        TaskDtlBo taskDtlBo = new TaskDtlBo();
        taskDtlBo.setTaskId(task.getId());
        taskDtlBo.setDelFlag("2");
        List<TaskDtl> dtls = taskDtlMapper.selectTaskDtl(taskDtlBo);
        if (dtls != null && dtls.size() > 0) {
            dtls.stream().forEach(item -> {
                item.setDelFlag("0");
            });
            taskDtlMapper.updateTaskDtlBatchById(dtls);
        }

        switch (task.getType()) {
            case "0":
                warehouse = warehouseMapper.selectWarehouseByTaskId(id);
                break;
            case "2":
                dealList = dealMapper.selectDealListByTaskId(id);
                exWarehouse = exWarehouseMapper.selectExWarehouseByTaskId(id);
                break;
            default:
                exWarehouse = exWarehouseMapper.selectExWarehouseByTaskId(id);
                break;
        }
        /**
         * 撤销下发信息
         */
        if (ObjectUtil.isNotNull(warehouse) && StringUtils.isNotEmpty(warehouse.getId())) {
            warehouse.setDelFlag("0");
            warehouse.setUpdateBy(LoginHelper.getUsername());
            warehouse.setUpdateTime(new Date());
            warehouseMapper.updateWarehouse(warehouse);

            WarehouseDtlBo warehouseDtlBo = new WarehouseDtlBo();
            warehouseDtlBo.setWid(warehouse.getId());
            warehouseDtlBo.setDelFlag("2");
            List<WarehouseDtl> items = warehouseDtlMapper.selectWarehouseDtl(warehouseDtlBo);

            if (items != null && items.size() > 0) {
                for (WarehouseDtl dtl : items) {
                    dtl.setDelFlag("0");
                }
                warehouseDtlMapper.updateWarehouseDtlBatchById(items);
            }
        }

        if (ObjectUtil.isNotNull(exWarehouse) && StringUtils.isNotEmpty(exWarehouse.getId())) {
            exWarehouse.setDelFlag("0");
            exWarehouse.setUpdateBy(LoginHelper.getUsername());
            exWarehouse.setUpdateTime(new Date());
            exWarehouseMapper.updateExWarehouse(exWarehouse);

            ExWarehouseDtlBo exWarehouseDtlBo = new ExWarehouseDtlBo();
            exWarehouseDtlBo.setWid(exWarehouse.getId());
            exWarehouseDtlBo.setDelFlag("2");
            List<ExWarehouseDtl> items = exWarehouseDtlMapper.selectExWarehouseDtl(exWarehouseDtlBo);

            if (items != null && items.size() > 0) {
                for (ExWarehouseDtl dtl : items) {
                    dtl.setDelFlag("0");
                    exWarehouseDtlMapper.updateById(dtl);
                }
                exWarehouseDtlMapper.updateExWarehouseDtlBatchById(items);
            }
        }

        /**
         * 处置审核恢复
         */
        if (dealList != null && dealList.size() > 0) {
            dealList.stream().forEach(deal -> {
                deal.setDelFlag("0");
                deal.setUpdateBy(LoginHelper.getUsername());
                deal.setUpdateTime(new Date());
                dealMapper.updateDeal(deal);
                DealDtlBo dtlBo = new DealDtlBo();
                dtlBo.setDealId(deal.getId());
                dtlBo.setDelFlag("2");
                List<DealDtl> ddtls = dealDtlMapper.selectDealDtl(dtlBo);
                if (ddtls != null && ddtls.size() > 0) {
                    ddtls.stream().forEach(item -> {
                        item.setDelFlag("0");
                    });
                    dealDtlMapper.updateDealDtlBatchById(ddtls);
                }

            });
        }

        Order order = orderMapper.selectOrderByID(id);

        if (ObjectUtil.isNotNull(order) && StringUtils.isNotEmpty(order.getId())) {
            order.setDelFlag("0");
            order.setUpdateBy(LoginHelper.getUsername());
            order.setUpdateTime(new Date());
            orderMapper.updateOrder(order);

            OrderDtlBo orderDtlBo = new OrderDtlBo();
            orderDtlBo.setOrderId(order.getId());
            orderDtlBo.setDelFlag("2");
            List<OrderDtl> items = orderDtlMapper.selectOrderDtlsByOrderId(orderDtlBo);

            if (items != null && items.size() > 0) {
                for (OrderDtl dtl : items) {
                    dtl.setDelFlag("0");
                }
                orderDtlMapper.updateOrderDtlBatchById(items);
            }

            List<OrderLog> logs = orderLogMapper.selectOrderLogsById(order.getId());
            if (logs != null && logs.size() > 0) {
                for (OrderLog dtl : logs) {
                    dtl.setDelFlag("0");
                }
                orderLogMapper.updateOrderLogBatchById(logs);
            }

            /**
             * 已派单运单恢复
             */
            Waybill waybill = waybillMapper.selectWaybillByOrderId(order.getId());

            if (ObjectUtil.isNotNull(waybill) && StringUtils.isNotEmpty(waybill.getId())) {
                waybill.setDelFlag("0");
                waybill.setUpdateBy(LoginHelper.getUsername());
                waybill.setUpdateTime(new Date());
                waybillMapper.updateWaybill(waybill);

                WaybillDtlBo waybillDtlBo = new WaybillDtlBo();
                waybillDtlBo.setWaybillId(waybill.getId());
                waybillDtlBo.setDelFlag("2");
                List<WaybillDtl> wDtls = waybillDtlMapper.selectWaybillDtlsByWid(waybillDtlBo);

                if (wDtls != null && wDtls.size() > 0) {
                    for (WaybillDtl dtl : wDtls) {
                        dtl.setDelFlag("0");
                    }
                    waybillDtlMapper.updateWaybillDtlBatchById(wDtls);
                }

                WaybillLogBo waybillLogBo = new WaybillLogBo();
                waybillLogBo.setTrackId(waybill.getId());
                waybillLogBo.setDelFlag("2");
                List<WaybillLog> wLogs = waybillLogMapper.selectWaybillLogListByWid(waybillLogBo);

                if (wLogs != null && wLogs.size() > 0) {
                    for (WaybillLog dtl : wLogs) {
                        dtl.setDelFlag("0");
                    }
                    waybillLogMapper.updateWaybillLogBatchById(wLogs);
                }
            }
        }

        /**
         * 操作日志恢复 operatorlog
         */
        OperatorLogBo operatorLogBo = new OperatorLogBo();
        operatorLogBo.setObjid(id);
        operatorLogBo.setDelFlag("2");
        List<OperatorLog> operatorLogs = operatorLogMapper.operatorLogList(operatorLogBo);
        if (operatorLogs != null && operatorLogs.size() > 0) {
            for (OperatorLog dtl : operatorLogs) {
                dtl.setDelFlag("0");
            }
            operatorLogMapper.updateOperatorLogBatchById(operatorLogs);
        }

        /**
         * 物品日志恢复 propertylog
         */


        dtls.stream().forEach(item -> {

            if (task.getType().equals("0") && StringUtils.isBlank(task.getReturnId())) {
                Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, item.getPno()));

                if (property.getTransferStatus().equals("2")) {
                    throw new ServiceException("当前物品已移交，无法恢复该订单！");
                }

                property.setTransferStatus("2");//更新为已移交
                propertyMapper.updateById(property);
            }

            /**
             * 恢复移交登记以外的物品日志记录
             */
            PropertyLogBo propertyLogBo = new PropertyLogBo();
            propertyLogBo.setPno(item.getPno());
            propertyLogBo.setDelFlag("2");
            List<PropertyLog> propertyLogs = propertyLogMapper.propertyLogList(propertyLogBo);
            if (propertyLogs != null && propertyLogs.size() > 0) {
                for (PropertyLog dtl : propertyLogs) {
                    dtl.setDelFlag("0");
                }
                propertyLogMapper.updatePropertyLogBatchById(propertyLogs);
            }
        });

//        commonService.saveOperatorLog(id,"oms","撤销订单");
        task.setUpdateBy(LoginHelper.getUsername());
        task.setUpdateTime(new Date());
        flag = baseMapper.updateTask(task) > 0;

        return flag;
    }

    @Override
    public TaskVo insertByAPI(TaskBo bo) {

        Task add = BeanUtil.toBean(bo, Task.class);
        add.setCreateBy("smscg");
        add.setUpdateBy("smscg");
        validEntityBeforeSave(add);

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        add.setSendStatus("0");
        add.setStatus("0");
        //设置来源 0-自主创建 1-市级下发
        add.setSource("1");

        String taskNo = "";
        //流转日志内容
        String operatorContent = "";
        //财物日志类型
        String logType = "";
        //订单类型
        String taskType = "";

        SysDept dept = deptMapper.selectVoOne(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptCode, bo.getDeptNo()));
        if (dept != null) {
            add.setDeptId(dept.getDeptId());
            add.setTakeDept(dept.getDeptId().intValue());
        }

        if (StringUtils.isNotEmpty(add.getType())) {
            switch (add.getType()) {
                case "0":
                    taskNo = "R";
                    operatorContent = "接收入库指令";
                    logType = "1";
                    taskType = "oms_warehouse";
                    break;
                case "1":
                    taskNo = "E";
                    operatorContent = "接收出库指令";
                    logType = "2";
                    taskType = "oms_exWarehouse";
                    break;
                case "3":
                    taskNo = "D";
                    operatorContent = "接收调用指令";
                    logType = "3";
                    taskType = "oms_transfer";
                    break;
                default:
                    break;
            }
        }
        add.setTaskNo(getNo(taskNo));//设置编号

        //设置是否车辆单
        if (!StringUtils.isEmpty(bo.getPropertyType()) && bo.getPropertyType().equals("3")) {
            add.setBuss("1");
        } else {
            add.setBuss("0");
        }

        //设置财物清单
        Long nums = 0l;
        List<TaskDtl> dtls = new ArrayList<>();
        List<PropertyLog> logs = new ArrayList<>();
        List<Inventory> inventories = new ArrayList<>();

        if (bo.getItems() != null && bo.getItems().size() > 0) {
            dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl, "id");
                dtl.setId(IdUtil.simpleUUID());
                dtl.setTaskId(add.getId());
                dtl.setDelFlag("0");
                dtl.setStatus("0");

                //财物处置方式
                if (add.getType().equals("2")) {
//                    dtl.setDealType(add.getDealType());
                    //附件
                    if (item.getOss() != null && item.getOss().size() > 0) {
                        List<SysOss> ossList = new ArrayList<>();
                        for (SysOss oss : bo.getOss()) {
                            oss.setBuss("dealDtl");
                            oss.setObjid(item.getId());
                            sysOssMapper.updateById(oss);
                            ossList.add(oss);
                        }
                        dtl.setOssList(ossList);
                    }
                }

                //判断当前入库,待移交财物进行移交操作
                Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, dtl.getPno()));
                if (property != null) {
                    //更新所队移交状态
                    property.setTransferStatus("2");
                    property.setBelongDeptId(storeMapper.selectStoreVoByID(add.getStoreId()).getDeptId());
                    //更新区县移交状态
//                    property.setCountyTransferStatus(finalCountyTransferStatus);
                    propertyMapper.updateById(property);
                }

                return dtl;
            }).collect(Collectors.toList());

            //计算财物数量
            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();

            for (TaskDtlVo item : bo.getItems()) {
                Long befores = 0L;
                Long count = 0L;
                Long afters = 0L;
                Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>()
                        .eq(Inventory::getPno, item.getPno())
                        .eq(Inventory::getDeptId, item.getDeptId())
                        .eq(Inventory::getStatus, "0"));
                if (inventory == null) {
                    continue;
                }
                befores = inventory.getNums();
                count = inventory.getNums();
                afters = befores - count;

                inventory.setStatus("1");//更新为不在库
                inventory.setNums(afters);
                addInventoryLog(inventory, befores, count, afters, add.getId(), add.getType());
                inventories.add(inventory);
            }
        }
        add.setNums(nums);


        boolean flag = baseMapper.insert(add) > 0;
        if (dtls != null && dtls.size() > 0) {
            taskDtlMapper.insertBatch(dtls);
        }

        //附件
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            for (SysOss oss : bo.getOss()) {
                oss.setBuss(taskType);
                oss.setObjid(add.getId());
                sysOssMapper.updateById(oss);
            }
        }

        String finalLogType = logType;
        String finalOperatorContent = operatorContent;

        LoginUser loginUser = LoginHelper.getLoginUser();
        logs = dtls.stream().map(item -> {
            String logContent = finalOperatorContent + "：(物品编号：" + item.getPno() + "，物品名称：" + item.getName() + "，申请说明：" + (StringUtils.isNotEmpty(add.getRemark()) ? add.getRemark() : "") + ")";
            return saveLog(finalLogType, item, add.getId(), add.getStoreId(), finalOperatorContent, add.getDeptId(), loginUser, item.getOssList());
        }).collect(Collectors.toList());

        if (logs != null && logs.size() > 0) {
//            propertyLogMapper.insertBatch(logs);
            //循环推送
            logs.forEach(item -> {
                PropertyLogModelsVo data = new PropertyLogModelsVo();
                data.setApi("proBase");
                data.setData(propertyLogMapper.selectPropertyLogVoByID(item.getId()));
                PushDatasUtil.pushPropertyDatas(data);
            });
        }

        //库存变动为不在库
        if (inventories != null && inventories.size() > 0) {
            inventoryMapper.updateBatchById(inventories);
        }

        if (flag) {
            bo.setId(add.getId());
            //操作日志
            addOperatorLog(add.getId(), "oms", operatorContent);
        }
        TaskVo vo = new TaskVo();
        BeanUtil.copyProperties(bo, vo);

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskVo insertTaskByAPI(TaskBo bo) {

        Task add = BeanUtil.toBean(bo, Task.class);
        add.setCreateBy("smscg");
        add.setUpdateBy("smscg");
        validEntityBeforeSave(add);

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        add.setSendStatus("0");
        add.setStatus("0");
        //设置来源 0-自主创建 1-市级下发
        add.setSource("1");

        String taskNo = "";
        //流转日志内容
        String operatorContent = "";
        //财物日志类型
        String logType = "";
        //订单类型
        String taskType = "";

        SysDept dept = deptMapper.selectVoOne(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptCode, bo.getDeptNo()));
        if (dept != null) {
            add.setDeptId(dept.getDeptId());
            add.setTakeDept(dept.getDeptId().intValue());
        }

        taskNo = "R";
        operatorContent = "接收入库指令";
        logType = "1";
        taskType = "oms_warehouse";
        add.setTaskNo(getNo(taskNo));//设置编号

        //设置是否车辆单
        if (!StringUtils.isEmpty(bo.getPropertyType()) && bo.getPropertyType().equals("3")) {
            add.setBuss("1");
        } else {
            add.setBuss("0");
        }

        //设置财物清单
        Long nums = 0L;
        List<TaskDtl> dtls = new ArrayList<>();

        if (bo.getItems() != null && bo.getItems().size() > 0) {
            dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl, "id");
                dtl.setId(IdUtil.simpleUUID());
                dtl.setTaskId(add.getId());
                dtl.setDelFlag("0");
                dtl.setStatus("0");
                return dtl;
            }).collect(Collectors.toList());

            //计算财物数量
            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();

        }
        add.setNums(nums);

        boolean flag = baseMapper.insert(add) > 0;
        if (dtls != null && dtls.size() > 0) {
            taskDtlMapper.insertBatch(dtls);
        }

        //附件
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            for (SysOss oss : bo.getOss()) {
                oss.setBuss(taskType);
                oss.setObjid(add.getId());
                sysOssMapper.updateById(oss);
            }
        }

        String finalLogType = logType;
        String finalOperatorContent = operatorContent;

//        dtls.stream().forEach(item->{
//            saveLog(finalLogType,item,add.getId(),add.getStoreId(),finalOperatorContent,add.getDeptId(),LoginHelper.getLoginUser(),item.getOssList());
//        });

        if (flag) {
            bo.setId(add.getId());
            //操作日志
            addOperatorLog(add.getId(), "oms", operatorContent);
        }
        TaskVo vo = new TaskVo();
        BeanUtil.copyProperties(bo, vo);

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskVo insertByOutWarehouseAPI(TaskBo bo) {

        Task add = BeanUtil.toBean(bo, Task.class);
        validEntityBeforeSave(add);
        TaskVo vo = null;
        /**
         * 默认配置
         */
        add.setId(IdUtil.simpleUUID());
        add.setStatus("0");
        add.setDelFlag("0");

        /**
         * 下发状态
         */
        add.setSendStatus("0");
        add.setSendReStatus("0");

        /**
         * 设置审核状态
         */
        if (!add.getType().equals("0") && !add.getType().equals("3")) {
            add.setCheckStatus("0");
        }
        /**
         * 来源
         */
        //设置来源 0-自主创建 1-市级下发
        add.setSource("1");

        String ossBuss = null;
        String head = null;
        String logType = null;
        String content = null;
        String orderType = null;
        String storeId = null;
        /**
         * type
         * 0-入库 1-出库 2-处置 3-调用
         */
        switch (bo.getType()) {
            case "0":
                head = "R";
                if (StringUtils.isNotBlank(bo.getReturnId())) {
                    ossBuss = "return_task";
                } else {
                    ossBuss = "oms_warehouse";
                }
                logType = PropertyLogType.WAREHOUSE_TASK.getCode();
                content = PropertyLogType.WAREHOUSE_TASK.getInfo();
                orderType = "入库";
                break;
            case "1":
                head = "E";
                ossBuss = "oms_exWarehouse";
                logType = PropertyLogType.EX_WAREHOUSE_TASK.getCode();
                content = PropertyLogType.EX_WAREHOUSE_TASK.getInfo();
                orderType = "出库";
                break;
            case "2":
                head = "C";
                ossBuss = "oms_deal";
                logType = PropertyLogType.DISPOSAL_TASK.getCode();
                content = PropertyLogType.DISPOSAL_TASK.getInfo();
                orderType = "处置";

                if (StringUtils.isEmpty(add.getIsTrailer())) {
                    add.setIsTrailer("0");//中心仓管处理授权 0-未授权 1-已授权
                }

                /**
                 * 处置申请
                 * 发还申请 dealType-3返回当事人
                 * 从发还申请提交的申请单 back
                 */
                if (StringUtils.isNotEmpty(bo.getSubmitType()) && bo.getSubmitType().equals("back") && bo.getDealType().equals("3")) {

                    TaskBo info = new TaskBo();
                    info.setPolice(bo.getPolice());
                    info.setPoliceTel(bo.getPoliceTel());
                    info.setBacker(bo.getBacker());
                    info.setBackTel(bo.getBackTel());
                    info.setBackCard(bo.getBackCard());
                    //身份证附件
                    if (bo.getBackOss() != null && bo.getBackOss().size() > 0) {
                        for (SysOss oss : bo.getBackOss()) {
                            oss.setObjid(add.getId());
                            oss.setBuss("backDeal");
                            sysOssMapper.updateById(oss);
                        }
                    }
                    add.setInfo(JsonUtils.toJsonString(info));

                }
                break;
            case "3":
                head = "D";
                ossBuss = "oms_transfer";
                logType = PropertyLogType.TRANSFER_TASK.getCode();
                content = PropertyLogType.TRANSFER_TASK.getInfo();
                orderType = "调用";
                break;
        }
        if (!bo.getIsPushTask()) {
            add.setTaskNo(getNo(head));//设置编号
        }
        List<TaskDtl> dtls = new ArrayList<>();
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            String finalContent = content;
            String finalLogType = logType;
            dtls = bo.getItems().stream().map(item -> {
                TaskDtl dtl = new TaskDtl();
                BeanUtil.copyProperties(item, dtl);
                dtl.setId(IdUtil.simpleUUID());
                dtl.setTaskId(add.getId());
                dtl.setDelFlag("0");
                dtl.setStatus("0");

                switch (add.getType()) {
                    case "2":
                        /**
                         * 处置类型
                         */
                        if (StringUtils.isNotEmpty(add.getDealType())) {
                            dtl.setDealType(add.getDealType());
                        }


                        InventoryVo inventoryVo = inventoryMapper.selectInventoryVoByPno(dtl.getPno());

                        /**
                         * 生成处置审核单
                         */

                        Deal dealAdd = new Deal();
                        dealAdd.setId(IdUtil.simpleUUID());
                        dealAdd.setTaskId(add.getId());
                        dealAdd.setStatus("0");
                        dealAdd.setDelFlag("0");
                        dealAdd.setIsFinish("0");//挑拣状态
                        dealAdd.setIsSign("0");//签收状态

                        dealAdd.setDealNo(dtl.getPno());
                        dealAdd.setDeptId(dtl.getDeptId());
                        dealAdd.setDealType(add.getDealType());
                        dealAdd.setNums(dtl.getNums());
                        dealAdd.setIsCheck("0");
                        dealAdd.setStoreId(add.getStoreId());
                        dealAdd.setMemo(add.getRemark());
                        dealMapper.insert(dealAdd);

                        DealDtl dealDtlAdd = new DealDtl();
                        BeanUtil.copyProperties(dealAdd, dealDtlAdd);
                        dealDtlAdd.setId(IdUtil.simpleUUID());
                        dealDtlAdd.setDealId(dealAdd.getId());
                        dealDtlAdd.setAreaId(inventoryVo != null ? inventoryVo.getAreaId() : null);
                        dealDtlAdd.setLocatorId(inventoryVo != null ? inventoryVo.getLocatorId() : null);
                        dealDtlAdd.setPno(dealAdd.getDealNo());
                        dealDtlAdd.setName(dtl.getName());
                        dealDtlAdd.setHandleUnitName(deptMapper.selectVoById(bo.getDeptId()).getDeptName());//处置单位
                        dealDtlMapper.insert(dealDtlAdd);

                        break;
                }
                /**
                 * 物品日志
                 */
                String info = JsonUtils.toJsonString(dtl);
                String logContent = finalContent + "：(物品编号：" + item.getPno() + "，物品名称：" + item.getName() + "，申请说明：" + (StringUtils.isNotEmpty(add.getRemark()) ? add.getRemark() : "") + ")";
                commonService.savePropertyLog(dtl.getPno(), add.getId(), dtl.getName(), finalLogType, logContent, dtl.getDeptId(), info, add.getStoreId(), dtl.getNums(), null);

                return dtl;
            }).collect(Collectors.toList());
        }
        Long nums = 0L;
        if (dtls.size() > 0) {
            taskDtlMapper.insertBatch(dtls);
            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();

            /**
             * 获取对应仓库
             */
            String pno = dtls.get(0).getPno();
            InventoryVo inventory = inventoryMapper.selectInventoryVoByPno(pno);
            if (inventory != null) {
                storeId = inventory.getStoreId();
            }
        }
        add.setNums(nums);//设置物品总数

        /**
         * 附件
         */
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            String finalBuss = ossBuss;
            bo.getOss().stream().forEach(oss -> {
                oss.setBuss(finalBuss);
                oss.setObjid(add.getId());
                sysOssMapper.updateById(oss);
            });
        }

        /**
         * buss 类型
         * 0-物品 1-车辆
         */
        StoreVo storeVo = null;
        if (StringUtils.isNotEmpty(storeId)) {
            storeVo = storeMapper.selectVoById(storeId);
            add.setStoreId(storeId);
        }

        if (storeVo != null) {
            if (storeVo.getName().equals("车辆仓")) {
                add.setBuss("1");
            } else {
                add.setBuss("0");
            }
        }

        boolean flag = baseMapper.insert(add) > 0;

        List<OperatorLog> oplogs = new ArrayList<>();
        if (flag) {
            //如果是归还单
            if (StringUtils.isNotBlank(add.getReturnId())) {
                Task dTask = baseMapper.selectTaskEntity(add.getReturnId());
                if (bo.getRevertMold().equals("0")) {
                    dTask.setReturnStatus("2");//已归还
                } else if (bo.getRevertMold().equals("1")) {
                    dTask.setReturnStatus("1");//部分归还
                }
                baseMapper.updateById(dTask);
            }

            oplogs.add(commonService.saveOperatorLog(add.getId(), "oms", content));//操作日志

            //数据推送
            if (StringUtils.isNotEmpty(add.getType())) {
                vo = baseMapper.selectTaskVoByID(add.getId());
                switch (add.getType()) {
                    case "0":
                        InTaskDatasVo data = BeanUtil.toBean(vo, InTaskDatasVo.class);
                        List<InTaskDatasDtlVo> items = dtls.stream().map(item -> {
                            InTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, InTaskDatasDtlVo.class);
                            return dvo;
                        }).collect(Collectors.toList());
                        data.setItems(items);
                        data.setLogs(oplogs);
                        PushDatasUtil.pushInTaskDatas(data);
                        break;
                    default:
                        OutTaskDatasVo outData = BeanUtil.toBean(vo, OutTaskDatasVo.class);
                        List<OutTaskDatasDtlVo> outItems = dtls.stream().map(item -> {
                            OutTaskDatasDtlVo dvo = BeanUtil.copyProperties(item, OutTaskDatasDtlVo.class);
                            return dvo;
                        }).collect(Collectors.toList());
                        outData.setItems(outItems);
                        outData.setLogs(oplogs);
                        PushDatasUtil.pushOutTaskDatas(outData);
                        break;
                }
            }

            /**
             * 新订单提醒
             */
            if (storeVo != null) {
                SmsRequest smsRequest = new SmsRequest();
                if (bo.getType().equals("2")) {
                    smsRequest.setTemplateCode(SmsTemplateCode.DISPOSAL_NOTICE.getSMS_CODE());
                    smsRequest.setPhoneNumber(userMapper.selectUserById(storeVo.getUserId()).getPhonenumber());
                    SmsTemplateParam templateParam = new SmsTemplateParam();
                    templateParam.setArea(deptMapper.getAreaName(bo.getDeptId()));
                    smsRequest.setTemplateParam(templateParam);
                    aliyunSmsService.AliyunSmsSend(smsRequest);

                    String dealPhone = configService.selectConfigByKey("app.oms.deal.phone");
                    if (!StringUtils.isEmpty(dealPhone)) {
                        smsRequest.setPhoneNumber(dealPhone);
                        aliyunSmsService.AliyunSmsSend(smsRequest);
                    }
                } else {
                    smsRequest.setTemplateCode(SmsTemplateCode.TASK_NOTICE.getSMS_CODE());
                    smsRequest.setPhoneNumber(userMapper.selectUserById(storeVo.getUserId()).getPhonenumber());
                    SmsTemplateParam templateParam = new SmsTemplateParam();
                    templateParam.setOrderType(orderType);
                    templateParam.setOrderCode(add.getTaskNo());
                    templateParam.setArea(deptMapper.getAreaName(bo.getDeptId()));
                    smsRequest.setTemplateParam(templateParam);
                    aliyunSmsService.AliyunSmsSend(smsRequest);
                }

            }
        }

        return vo;
    }

    public String getNo(String num) {
//        LambdaQueryWrapper<Task> lqw = Wrappers.lambdaQuery();
//        Long maxNumObject = baseMapper.selectCount(lqw);
        Long maxNumObject = baseMapper.selectCountAlls();
//        String num = "";
        String todayStr = DateUtils.date2String(new Date(), "yyMMdd");

        if (maxNumObject == null) {
            num += todayStr + "000001";
        } else {
            String maxnumStr = "00000" + maxNumObject.toString();
            String maxnumNo = maxnumStr.substring(maxnumStr.length() - 6, maxnumStr.length());
            String nextnumNo = StringUtils.nextNo(maxnumNo, 6);
            num += todayStr + nextnumNo;
        }
        return num;
    }

    //日志添加
    public OperatorLog addOperatorLog(String objid, String type, String content) {

        OperatorLog log = new OperatorLog();
        log.setId(IdUtil.simpleUUID());
        log.setObjid(objid);
        log.setDelFlag("0");
        log.setLogTime(new Date());
        if (LoginHelper.checkLoginUser()) {
            log.setUserId(LoginHelper.getUserId());
            log.setOperator(LoginHelper.getNickname());
        } else {
            log.setOperator("数据同步");
        }
        log.setLogType(type);
        log.setContent(content);
        logMapper.insert(log);
        return log;
    }

    //财物日志添加
    private PropertyLog saveLog(String logType, TaskDtl dtl, String objid, String storeId, String content, Long deptId, LoginUser loginUser, List<SysOss> osses) {

        PropertyLog propertyLog = new PropertyLog();
        BeanUtil.copyProperties(dtl, propertyLog, "id");
        propertyLog.setId(IdUtil.simpleUUID());
        propertyLog.setObjid(objid);
        propertyLog.setLogTime(new Date());
        propertyLog.setLogType(logType);//0-移交登记 1-入库 2-出库 3-调用 4-处置 5-交接 6-上架 7-挑拣
        propertyLog.setContent(content);
        propertyLog.setReceiveDept(dtl.getDeptId());
        propertyLog.setStoreId(storeId);
        if (loginUser != null) {
            propertyLog.setUserId(loginUser.getUserId());
            propertyLog.setOperator(loginUser.getNickName());
            SysDept dept = deptMapper.selectById(loginUser.getDeptId());

            propertyLog.setNode(PropertyLogNode.getNodeCodeByBuss(dept.getLevel(), logType));
        } else {
            propertyLog.setOperator("--");
            propertyLog.setNode(PropertyLogNode.getNodeCodeByBuss(3L, logType));
        }
        propertyLog.setInfo(JsonUtils.toJsonString(dtl));
        propertyLog.setDelFlag("0");

        propertyLogMapper.insert(propertyLog);
        if (osses != null && osses.size() > 0) {
            for (SysOss oss : osses) {
                SysOss copyOss = new SysOss();
                BeanUtil.copyProperties(oss, copyOss, "ossId");
                copyOss.setObjid(propertyLog.getId());
                copyOss.setBuss("propertyLog");
                sysOssMapper.insert(copyOss);
            }
        }
        return propertyLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTaskNums() {

        boolean flag = false;
        List<Task> taskList = baseMapper.selectList(new LambdaQueryWrapper<Task>().eq(Task::getNums, 0).eq(Task::getDelFlag, "0"));
        if (taskList != null && taskList.size() > 0) {
            taskList.stream().forEach(item -> {
                TaskDtlBo dtlBo = new TaskDtlBo();
                dtlBo.setTaskId(item.getId());
                List<TaskDtlVo> dtls = taskDtlMapper.selectTaskDtlList(dtlBo);
                if (dtls != null && dtls.size() > 0) {
                    Long nums = dtls.stream().mapToLong(dtl -> dtl.getNums()).sum();
                    item.setNums(nums);
                }
            });
            flag = baseMapper.updateBatchById(taskList);
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateOrderWithWaybill() {

        List<OrderVo> orderList = orderMapper.selectOrderNotInDtl();
        if (orderList != null && orderList.size() > 0) {
            orderList.stream().forEach(orderVo -> {
                TaskVo taskVo = baseMapper.selectTaskVoByID(orderVo.getTaskId());
                WarehouseVo warehouseVo = warehouseMapper.selectWarehouseVoByTaskId(taskVo.getId());

                TaskDtlBo taskDtlBo = new TaskDtlBo();
                taskDtlBo.setTaskId(taskVo.getId());
                List<TaskDtlVo> items = taskDtlMapper.selectTaskDtlList(taskDtlBo);

                List<WarehouseDtl> warehouseDtls = items.stream().map(item -> {
                    WarehouseDtl dtl = new WarehouseDtl();
                    BeanUtil.copyProperties(item, dtl, "id");

                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setWid(warehouseVo.getId());
                    dtl.setStatus("0");
                    dtl.setDelFlag("0");
                    return dtl;
                }).collect(Collectors.toList());
                warehouseDtlMapper.insertBatch(warehouseDtls);

                List<OrderDtl> orderDtls = items.stream().map(item -> {
                    OrderDtl dtl = new OrderDtl();
                    BeanUtil.copyProperties(item, dtl, "id");

                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setOrderId(orderVo.getId());
                    dtl.setStatus("0");
                    dtl.setDelFlag("0");

                    return dtl;
                }).collect(Collectors.toList());
                orderDtlMapper.insertBatch(orderDtls);

                WaybillVo waybillVo = waybillMapper.selectWaybillVoByOrderID(orderVo.getId());
                List<WaybillDtl> waybillDtls = items.stream().map(item -> {
                    WaybillDtl dtl = new WaybillDtl();
                    BeanUtil.copyProperties(item, dtl, "id");

                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setWaybillId(waybillVo.getId());
                    dtl.setStatus("0");
                    dtl.setDelFlag("0");
                    if (orderVo.getStatus().equals("3")) {
                        dtl.setSignStatus("1");
                    } else {
                        dtl.setSignStatus("0");
                    }

                    return dtl;
                }).collect(Collectors.toList());
                waybillDtlMapper.insertBatch(waybillDtls);

            });
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePics(String taskNo) {

        boolean flag = true;
        String[] ignoreProperties = {"ossId", "createBy", "createTime", "updateBy", "updateTime"};
        Task task = baseMapper.selectOne(new LambdaQueryWrapper<Task>().eq(Task::getTaskNo, taskNo));

        if (task == null) {
            throw new ServiceException("当前编号不存在");
        }

        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getTaskId, task.getId()));
        if (order == null) {
            throw new ServiceException("无效订单");
        }

        Handover handover = handoverMapper.selectOne(new LambdaQueryWrapper<Handover>().eq(Handover::getObjid, task.getId()).eq(Handover::getType, "0"));
        if (handover == null) {
            throw new ServiceException("系统异常");
        }
        HandoverDtlBo dtlBo = new HandoverDtlBo();
        dtlBo.setHid(handover.getId());
        dtlBo.setDelFlag("0");
        List<HandoverDtlVo> dtls = handoverDtlMapper.selectHandoverDtlList(dtlBo);

        if (dtls == null || dtls.size() == 0) {
            throw new ServiceException("系统加载异常");
        }
        HandoverDtlVo dtlVo = dtls.get(0);
        SysOssBo ossBo = new SysOssBo();
        ossBo.setBuss("handoverDtl");
        ossBo.setObjid(dtlVo.getId());
        List<SysOss> ossList = sysOssMapper.selectSysOssList(ossBo);

        if (ossList == null || ossList.size() == 0) {
            throw new ServiceException("查无此图");
        }
        ossList.stream().forEach(item -> {
            SysOss newOss = new SysOss();
            BeanUtil.copyProperties(item, newOss, ignoreProperties);
            newOss.setBuss("facade");
            newOss.setObjid(order.getId());
            sysOssMapper.insert(newOss);
        });

        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHandoverFile() {

        TaskBo taskBo = new TaskBo();
        taskBo.setStatus("1");
        List<TaskVo> list = baseMapper.selectTaskVoList(taskBo);
        if (list != null && list.size() > 0) {
            for (TaskVo vo : list) {
                /**
                 * 查询是否已签收
                 */
                HandoverBo bo = new HandoverBo();
                bo.setObjid(vo.getId());
                bo.setType("1");
                bo.setStatus("1");
                HandoverVo handoverVo = handoverMapper.selectHandoverVoByObjid(bo);
                if (handoverVo != null) {
                    /**
                     * 查询交接原件
                     */
                    SysOssBo ossBo = new SysOssBo();
                    ossBo.setObjid(vo.getId());
                    ossBo.setBuss("handoverDtl");
                    List<SysOss> ossList = sysOssMapper.selectOssList(ossBo);

                    if (ossList == null || ossList.size() == 0) {
                        ossBo.setObjid(handoverVo.getId());
                        List<SysOss> handoverOss = sysOssMapper.selectOssList(ossBo);
                        if (handoverOss != null && handoverOss.size() > 0) {
                            SysOss oss = handoverOss.get(0);
                            oss.setObjid(vo.getId());
                            sysOssMapper.updateById(oss);
                        }
                    }

                }
            }
        }
    }

    @Override
    public Boolean updateWarehouseNums() {

        boolean flag = false;
        List<Warehouse> warehouseList = warehouseMapper.selectList(new LambdaQueryWrapper<Warehouse>().eq(Warehouse::getNums, 0).eq(Warehouse::getDelFlag, "0"));
        if (warehouseList != null && warehouseList.size() > 0) {
            warehouseList.stream().forEach(item -> {
                WarehouseDtlBo dtlBo = new WarehouseDtlBo();
                dtlBo.setWid(item.getId());
                List<WarehouseDtlVo> dtls = warehouseDtlMapper.selectWarehouseDtlList(dtlBo);
                if (dtls != null && dtls.size() > 0) {
                    Long nums = dtls.stream().mapToLong(dtl -> dtl.getNums()).sum();
                    item.setNums(nums);
                }
            });
            flag = warehouseMapper.updateBatchById(warehouseList);
        }
        return flag;
    }

    @Override
    public Map<String, Object> countWeekWithTask(TaskBo task) {

        return baseMapper.countWeekWithTask(task);
    }

    @Override
    public Long selectCountTask(TaskBo task) {

        return baseMapper.selectCountTask(task);
    }

    @Override
    public Boolean reviewOss(String id, List<SysOss> oss) {

        List<SysOss> update = new ArrayList<>();
        if (oss != null && oss.size() > 0) {
            update = oss.stream().map(item -> {
                item.setBuss("handoverDtl");
                item.setObjid(id);
                return item;
            }).collect(Collectors.toList());
        }
        return sysOssMapper.updateBatchById(update);
    }

    @Override
    public Task checkTask(TaskVo vo) {

        Task task = baseMapper.selectById(vo.getId());
        task.setCheckStatus(vo.getCheckStatus());
        task.setCheckTime(new Date());
        task.setChecker(LoginHelper.getUsername());
        task.setDispatcherId(LoginHelper.getUserId());
        baseMapper.updateById(task);
        return task;
    }

    @Override
    public TaskVo uploadVideo(TaskVo vo) {

        if (vo.getVideoList() != null && vo.getVideoList().size() > 0) {
            List<SysOss> update = new ArrayList<>();
            update = vo.getVideoList().stream().map(item -> {
                item.setBuss("taskVideo");
                item.setObjid(vo.getId());
                return item;
            }).collect(Collectors.toList());
            if (update.size() > 0) {
                sysOssMapper.updateBatchById(update);
            }
        }
        SysOssBo bo = new SysOssBo();
        bo.setBuss("taskVideo");
        bo.setObjid(vo.getId());
        List<SysOss> videoList = sysOssMapper.selectSysOssList(bo);
        vo.setVideoList(videoList);
        return vo;
    }

    @Override
    public TableDataInfo<CancelTaskBo> cancelTaskList(CancelTaskBo bo, PageQuery pageQuery) {

        String beginTime = (String) bo.getParams().get("beginCreateTime");
        String endTime = (String) bo.getParams().get("endCreateTime");

        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<Task>()
                .eq(Task::getDelFlag, 2)
                .eq(Task::getDeptId, LoginHelper.getDeptId())
                .exists(StrUtil.isNotBlank(bo.getPno()),
                        StrUtil.format("SELECT 1 FROM T_TASK_DTL WHERE T_TASK.ID = TASK_ID AND PNO= '{}'", bo.getPno()))
                .between(StrUtil.isNotBlank(beginTime) && StrUtil.isNotBlank(endTime), Task::getUpdateTime, beginTime,
                        endTime);
        IPage<CancelTaskBo> cancelTaskBoIPage = baseMapper.cancelTaskList(pageQuery.build(), queryWrapper);
        return TableDataInfo.build(cancelTaskBoIPage);
    }

    @Override
    public List<DisposalApplyVo> getDisposalApplyList(TaskBo task) {

        return baseMapper.getDisposalApplyList(task);
    }

    @Override
    public boolean disposalFinish(String id) {

        Task task = new Task();
        task.setId(id);
        task.setStatus("1");

        return baseMapper.updateById(task) > 0;

    }

    /**
     * 库存日志新增
     * 0-接收登记 1-上架 2-挑拣 3-调用 4-处置
     */
    private InventoryLog addInventoryLog(Inventory inventory, Long befores, Long nums, Long afters, String objid, String type) {

        InventoryLog log = new InventoryLog();
        log.setId(IdUtil.simpleUUID());
        log.setStockId(inventory.getId());
        log.setStoreId(inventory.getStoreId());
        log.setDeptId(inventory.getDeptId());
        log.setBefores(befores);
        log.setNums(nums);
        log.setAfters(afters);
        log.setType(type);
        log.setReferId(objid);
        if (LoginHelper.checkLoginUser()) {
            log.setOperator(LoginHelper.getUsername());
        } else {
            log.setOperator("数据同步");
        }

        log.setStatus("0");
        log.setDelFlag("0");
//        inventoryLogMapper.insert(log);
        return log;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateHandoverPics(String taskId) {

        boolean flag = false;
        /**
         * 查询是否已签收
         */
        HandoverBo bo = new HandoverBo();
        bo.setObjid(taskId);
        bo.setType("1");
        bo.setStatus("1");
        HandoverVo handoverVo = handoverMapper.selectHandoverVoByObjid(bo);
        if (handoverVo != null) {
            /**
             * 查询交接原件
             */
            SysOssBo ossBo = new SysOssBo();
            ossBo.setObjid(taskId);
            ossBo.setBuss("handoverDtl");
            List<SysOss> ossList = sysOssMapper.selectSysOssList(ossBo);

            if (ossList == null || ossList.size() == 0) {
                ossBo.setObjid(handoverVo.getId());
                List<SysOss> handoverOss = sysOssMapper.selectSysOssList(ossBo);
                if (handoverOss != null && handoverOss.size() > 0) {
                    SysOss oss = handoverOss.get(0);
                    oss.setObjid(taskId);
                    flag = sysOssMapper.updateById(oss) > 0;
                }
            }

        }
        return flag;
    }

}
